我想将文件内容作为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文件,但这一次我收到了来自服务器的错误信息:
无法上传图片;格式不受支持
我怀疑这与编码有关。有人看出我做错了什么明显的事情吗?