且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java Http客户端通过POST上传文件

更新时间:2022-04-17 05:35:49

通过 HTTP 发送文件应该使用 multipart/form-data 编码进行.您的 servlet 部分很好,因为它已经使用 Apache Commons FileUpload 来解析 multipart/form-数据请求.

Sending files over HTTP is supposed to take place using multipart/form-data encoding. Your servlet part is fine as it already uses Apache Commons FileUpload to parse a multipart/form-data request.

然而,您的客户端部分显然不好,因为您似乎将文件内容原始写入请求正文.您需要确保您的客户端发送正确的 multipart/form-data 请求.具体如何执行取决于您用于发送 HTTP 请求的 API.如果它是普通的 java.net.URLConnection,那么您可以在 这个答案.如果您为此使用 Apache HttpComponents Client,那么这是一个具体的例子,取自 他们的文档:

Your client part, however, is apparently not fine as you're seemingly writing the file content raw to the request body. You need to ensure that your client sends a proper multipart/form-data request. How exactly to do it depends on the API you're using to send the HTTP request. If it's plain vanilla java.net.URLConnection, then you can find a concrete example somewhere near the bottom of this answer. If you're using Apache HttpComponents Client for this, then here's a concrete example, taken from their documentation:

String url = "https://example.com";
File file = new File("/example.ext");

try (CloseableHttpClient client = HttpClients.createDefault()) {
    HttpPost post = new HttpPost(url);
    HttpEntity entity = MultipartEntityBuilder.create().addPart("file", new FileBody(file)).build();
    post.setEntity(entity);

    try (CloseableHttpResponse response = client.execute(post)) {
        // ...
    }
}

与具体问题无关,您的服务器端代码中存在错误:


Unrelated to the concrete problem, there's a bug in your server side code:

File file = new File("files\"+item.getName());
item.write(file);

这可能会覆盖任何以前上传的同名文件.我建议使用 File#createTempFile() 代替.

This will potentially overwrite any previously uploaded file with the same name. I'd suggest to use File#createTempFile() for this instead.

String name = FilenameUtils.getBaseName(item.getName());
String ext = FilenameUtils.getExtension(item.getName());
File file = File.createTempFile(name + "_", "." + ext, new File("/files"));
item.write(file);