Java HTTP client uploads files through post
I am developing a J2ME client that must upload files to the servlet using HTTP
Use Apache Commons fileUpload to override the servlet part
protected void doPost(HttpServletRequest request,HttpServletResponse response) { ServletFileUpload upload = new ServletFileUpload(); upload.setSizeMax(1000000); File fileItems = upload.parseRequest(request); // Process the uploaded items Iterator iter = fileItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); File file = new File("\files\\"+item.getName()); item.write(file); } }
It seems that common upload can only upload multipart files, but there is no application / octect stream
However, for the client, there is no multipart class, and in this case, it is impossible to use any httpclient library
Other options might be to upload using HTTP chunk, but I haven't found a clear example of how to do this, especially in servlets
My choice is: – implement a servlet for HTTP chunk upload – implement the original client for HTTP multipart creation
I don't know how to execute any of the above options Any suggestions?
Solution
Sending files over HTTP should be encoded using multipart / form data Your servlet part is good because it already uses Apache Commons fileUpload to parse multipart / form data requests
However, your client part is obviously incorrect because you seem to write the contents of the file to the original request body You need to make sure that your client sends the correct multipart / form data request How you do this depends on the API you use to send HTTP requests If it is simple java net. Urlconnection, then you can find a specific example at the bottom of this answer If you use the Apache httpcomponents client example,
HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); multipartentity entity = new multipartentity(); entity.addPart("file",new FileBody(file)); post.setEntity(entity); HttpResponse response = client.execute(post); // ...
It has nothing to do with the specific problem. Your server-side code has an error:
File file = new File("\files\\"+item.getName()); item.write(file);
This may overwrite any previously uploaded files with the same name I recommend using file #createtempfile() instead
String name = FilenameUtils.getBaseName(item.getName()); String ext = FilenameUtils.getExtension(item.getName()); File file = File.createTempFile(name + "_","." + ext,new File("/files")); item.write(file);