send parameters while uploading file
I've got this piece of code http://pastebin.com/VrMNuxcv which successfully uploads a file onto the server from my android.
I have to send a couple of string parameters together with it.
For that i have given
conn.setRequestProperty("x-myapp-param1", "Parameter 1 text");
On the server side (Servlet DoPsot method)
I tried to retrieve the string parameter by
String userId = request.getParameter("myapp-param1");
But the
userId is null
My code in the client part is given below:
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a HTTP
// connection to
// the URL
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("file_name", fileName);
conn.setRequestProperty("x-myapp-param1", "Parameter 1 text");
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file_name\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available
();
Server code:
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userId = request.getParameter("myapp-param1");
String x_user_id = request.getParameter("x-myapp-param1");
System.out.println("userId getParameter : "+userId +"x_user_id : "+ x_user_id);
System.out.println("request.getHeaderNames();"+request.开发者_如何学运维getHeaderNames());
System.out.println("request.getHeaderNames();"+request.getHeaders("x"));
File filenameImg = null;
List<FileItem> items = null;
try {
items = new ServletFileUpload(new DiskFileItemFactory())
.parseRequest(request);
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form fields here the same way as
// request.getParameter().
// You can get parameter name by
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
System.out.println("user_id===fieldname======: "+fieldname);
//System.out.println("user_id====fieldvalue=====: "+fieldvalue);
// You can get parameter value by item.getString();
} else {
try{
// Process uploaded fields here.
String filename = FilenameUtils.getName(item.getName());
// Get filename.
String path = GetWebApplicationPathServlet.getContext().getRealPath("/images");
File file = new File(path,filename);
// Define destination file.
item.write(file);
System.out.println("filename: "+filename);
System.out.println("file: "+file);
request.setAttribute("image", file);
filenameImg = file;
// Write to destination file.
// request.setAttribute("image", filename);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
There are two major problems:
The
URLConnection#setRequestProperty()
sets the HTTP request header, not the HTTP request parameter. Those are two entirely different things. In case ofmultipart/form-data
requests, you need to write them as a fullworthy multipart part. You can find a detailed example in this answer (check the section Uploading Files near the bottom).In case of a HTTP
multipart/form-data
request, the parameters are not available byHttpServletRequest#getParameter()
. You need to treat them as multipart parts and not as request parameters. You can parse them using Apache Commons FileUpload, or when you're already on Servlet 3.0, usingHttpServletRequest#getParts()
. You're already using Apache Commons FileUpload, so just keep that part and get rid of the unnecessarygetParameter()
calls. The regular parameters are available in the secion commented as "Process regular form fields here".
Check the spelling
You do
conn.setRequestProperty("x-myapp-param1", "Parameter 1 text");
and
String userId = request.getParameter("myapp-param1");
Notice the missing x- on the receiver side.
I realized my Fileupload by adding the appace-mime libarys, they support entities.
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT);
for(int index=0; index < nameValuePairs.size(); index++) {
ContentBody cb;
if(nameValuePairs.get(index).getName().equalsIgnoreCase("File")) {
File file = new File(nameValuePairs.get(index).getValue());
FileBody isb = new FileBody(file,"application/*");
/*
byte[] data = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(data);
fis.close();
ByteArrayBody bab = new ByteArrayBody(data,"application/*","File");
entity.addPart(nameValuePairs.get(index).getName(), bab);
*/
entity.addPart(nameValuePairs.get(index).getName(), isb);
} else {
// Normal string data
cb = new StringBody(nameValuePairs.get(index).getValue(),"", null);
entity.addPart(nameValuePairs.get(index).getName(),cb);
}
}
httpost.setEntity(entity);
精彩评论