I want to send the contents of a file as org.apache.http.entity.mime.MultipartEntity . The problem is that I actually do not have a file, but only with the contents of String . The following test works fine, where file is java.io.File pointing to a valid png 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()));
Later I will not have a real file, but its contents will be String . I am not very good at coding (not to mention this), but if I try to use the same approach with a temporary file that was created as follows
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 points to exactly the same png file that succeeded in the first block of code, but this time I get
Failed to load image; format not supported
error from server. I suspect it has something to do with the encoding. Does anyone see what obvious thing I did wrong?
source share