我想将文件的内容作为 org.apache.http.entity.mime.MultipartEntity
发送。问题是,我实际上没有文件,只有 String
形式的内容。以下测试完美运行,其中 file
是指向有效 png 文件的 java.io.File
:
MultipartEntity entity =
new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("source", new StringBody("computer"));
entity.addPart("filename", new FileBody(file, "image/png"));
HttpPost httpPost = new HttpPost(URL);
httpPost.setEntity(entity);
HttpClient httpClient = new DefaultHttpClient();
final HttpResponse response = httpClient.execute(httpPost);
System.out.println(EntityUtils.toString(response.getEntity()));
稍后,我不会有一个真正的文件,而只有它的内容作为 String
。我对编码知之甚少(更不用说什么了)但是如果我尝试使用以下列方式创建的临时文件的相同方法
String contents = FileUtils.readFileToString(new File(path),"UTF8");
File tmpFile = File.createTempFile("image", "png");
tmpFile.deleteOnExit();
InputStream in = new ByteArrayInputStream(contents.getBytes("UTF8"));
FileOutputStream out = new FileOutputStream(tmpFile);
org.apache.commons.io.IOUtils.copy(in, out);
path
指向在第一个代码块中成功的完全相同的 png 文件,但这次我得到一个
Failed to upload image; the format is not supported
来自服务器的错误。我怀疑与编码有关。有人看到我做错了什么明显的事情吗?
最佳答案
不要使用readFileToString,而是使用readFileToByteArray,并且不要将内容存储在String中,而是存储在byte[]中:
byte[] contents = FileUtils.readFileToByteArray(new File(path));
File tmpFile = File.createTempFile("image", "png");
tmpFile.deleteOnExit();
InputStream in = new ByteArrayInputStream(contents);
FileOutputStream out = new FileOutputStream(tmpFile);
org.apache.commons.io.IOUtils.copy(in, out);
关于java - 将虚拟文件作为 MultipartEntity 发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17354712/