将虚拟文件作为MultipartEntity发送

4

我想将文件内容作为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文件,但这一次我收到了来自服务器的错误信息:

无法上传图片;格式不受支持

我怀疑这与编码有关。有人看出我做错了什么明显的事情吗?


看起来,“contents”是一个二进制文件,不能被转换成字符串。 - morgano
1个回答

6
不要使用readFileToString,而是使用readFileToByteArray,并且不要将内容存储在字符串中,而应存储在字节数组中:
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);

谢谢。我自己想不到使用String,但在Mathematica和Java之间的接口在这种情况下有点不清楚。虽然我可以用StringMathematica中表示甚至二进制的东西,但当我将其发送到Java时,它会出现问题。无论如何,将其转换为数字(字节)列表效果很好。 - halirutan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接