我需要将 tar.gzip 文件从一个 java 应用程序(通过 Servlet)发送到另一个应用程序 - 我使用带有 MultipartEntity 的 HTTP 客户端来实现此目的。
在文件传输过程中,文件的大小似乎增加了一倍 - 就好像它正在被解压缩一样 - 并且它不再被识别为 tar.gz 或 tar 文件。
这是发送方法:
HttpClient http = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
MultipartEntity multipart = new MultipartEntity();
ContentBody fileContent = new FileBody(file, "application/octet-stream");
ContentBody pathContent = new StringBody(file.getAbsolutePath());
multipart.addPart("package", fileContent);
multipart.addPart("path", pathContent);
post.setEntity(multipart);
HttpResponse response = null;
try {
response = http.execute(post);
StringWriter sw = new StringWriter();
IOUtils.copy(response.getEntity().getContent(), sw);
} catch (Exception ex){
log.error("Unable to POST to ["+url+"].",ex);
}
return result;
这是上面代码 POST 到的 servlet 方法:
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
log.info("File transfer request received, collecting file information and saving to server.");
Part filePart = req.getPart("package");
Part filePathPart = req.getPart("path");
StringWriter sw = new StringWriter();
IOUtils.copy(filePathPart.getInputStream(), sw);
String path = sw.getBuffer().toString();
File outputFile = new File(path);
FileWriter out = new FileWriter(outputFile);
IOUtils.copy(filePart.getInputStream(), out);
log.info("File ["+path+"] has been saved to the server.");
out.close();
sw.close();
}
我不是这方面的专家 - 而且 Google 似乎没有提供太多帮助...任何帮助都会很棒。
谢谢, 皮特
最佳答案
您的具体问题是因为您在此处使用 FileWriter
而不是 FileOutputStream
将传入字节转换为字符:
FileWriter out = new FileWriter(outputFile);
ZIP 文件是二进制文件,由特定的字节序列表示,而不是文本、HTML、XML 等字 rune 件。通过这种方式将字节转换为字符,您只会对原始二进制内容进行变形,从而导致文件不再被识别为 ZIP 文件。您最终会得到一个损坏的文件。
如果您改用FileOutputStream
,那么您的问题就会得到解决。完全没有必要用 Commons FileUpload 来替换这一切。
另请参阅:
与具体问题无关,出于安全原因,在服务器端重用客户端特定的绝对路径并不是一个好主意,但您迟早会发现这一点。而是最多重用文件名,最好与 File#createTempFile() 结合使用来自动生成唯一的文件名后缀。
关于Java - 使用 Apache Http 客户端发布 GZIP 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12298087/