【问题标题】:send parameters while uploading file上传文件时发送参数
【发布时间】:2011-07-29 01:16:35
【问题描述】:

我有这段代码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();
                }

            }
        }

【问题讨论】:

    标签: android servlets upload httpconnection


    【解决方案1】:

    检查拼写

    你会的

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

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

    注意接收端缺少的 x-。

    【讨论】:

    • 我添加了 String x_user_id = request.getParameter("x-myapp-param1");在我的代码中也是如此。但值仍然为空
    【解决方案2】:

    我通过添加 appace-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);
    

    【讨论】:

    【解决方案3】:

    主要有两个问题:

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

    2. 在 HTTP multipart/form-data 请求的情况下,HttpServletRequest#getParameter() 无法使用参数。您需要将它们视为多部分,而不是请求参数。您可以使用Apache Commons FileUpload 解析它们,或者当您已经使用Servlet 3.0 时,使用HttpServletRequest#getParts()。您已经在使用 Apache Commons FileUpload,所以只需保留该部分并摆脱不必要的 getParameter() 调用。常规参数在注释为“在此处处理常规表单字段”的部分中可用。

    【讨论】:

      猜你喜欢
      • 2011-07-16
      • 2019-02-13
      • 2014-02-14
      • 1970-01-01
      • 2014-02-23
      • 2014-07-14
      • 2013-12-08
      • 2011-06-27
      • 1970-01-01
      相关资源
      最近更新 更多