上传文件时发送参数
我有这段代码 http://pastebin.com/VrMNuxcv 成功将文件上传到服务器来自我的安卓。
我必须将几个字符串参数与它一起发送。
为此,我
conn.setRequestProperty("x-myapp-param1", "Parameter 1 text");
在服务器端(Servlet DoPsot 方法)
给出了我尝试通过以下方式检索字符串参数
String userId = request.getParameter("myapp-param1");
但
userId is null
客户端部分中的我的代码如下:
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
();
服务器代码:
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();
}
}
}
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();
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有两个主要问题:
URLConnection#setRequestProperty()
设置 HTTP 请求标头,而不是 HTTP 请求参数。这是完全不同的两件事。如果是multipart/form-data
请求,您需要将它们编写为完整的多部分部分。您可以在 此中找到详细示例答案(检查底部附近的上传文件部分)。如果是 HTTP
multipart/form-data
请求,参数无法通过HttpServletRequest#getParameter()
。您需要将它们视为多部分,而不是请求参数。您可以使用 Apache Commons FileUpload 来解析它们,或者当您已经使用 Servlet 3.0 时,使用HttpServletRequest#getParts()
。您已经在使用 Apache Commons FileUpload,因此只需保留该部分并删除不必要的getParameter()
调用即可。常规参数在注释为“在此处处理常规表单字段”的部分中可用。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".拼写
检查您所做的
并
注意接收方缺少的 x-。
Check the spelling
You do
and
Notice the missing x- on the receiver side.
我通过添加 appace-mime 库来实现我的 Fileupload,它们支持实体。
I realized my Fileupload by adding the appace-mime libarys, they support entities.