上传文件时发送参数

时间:2011-04-04 09:41:50

标签: android servlets upload httpconnection

我已经有了这段代码http://pastebin.com/VrMNuxcv,它可以从我的android成功将文件上传到服务器上。

我必须与它一起发送几个字符串参数。

为此我已经给出了

 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();
                }

            }
        }

3 个答案:

答案 0 :(得分:4)

有两个主要问题:

  1. URLConnection#setRequestProperty()设置HTTP请求标头,而不是HTTP请求参数。这是两件完全不同的事情。如果是multipart/form-data个请求,您需要将它们写为完整的多部分。您可以在this answer中找到详细示例(请查看底部附近的上传文件部分)。

  2. 如果发出HTTP multipart/form-data请求,则HttpServletRequest#getParameter()无法使用这些参数。您需要将它们视为多部分而不是请求参数。您可以使用Apache Commons FileUpload或使用HttpServletRequest#getParts()在Servlet 3.0上解析它们。您已经在使用Apache Commons FileUpload,因此请保留该部分并消除不必要的getParameter()调用。常规参数在secion中可用,在此处标注为“处理常规表单字段”。

答案 1 :(得分:1)

检查拼写

你做

conn.setRequestProperty("x-myapp-param1", "Parameter 1 text"); 

String userId = request.getParameter("myapp-param1");

注意接收方缺少x-。

答案 2 :(得分:1)

我通过添加apache-mime库实现了我的Fileupload,它们支持实体。

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);