上传文件时发送参数

发布于 2024-10-30 03:22:00 字数 4040 浏览 4 评论 0原文

我有这段代码 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

软甜啾 2024-11-06 03:22:00

有两个主要问题:

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

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

There are two major problems:

  1. The URLConnection#setRequestProperty() sets the HTTP request header, not the HTTP request parameter. Those are two entirely different things. In case of multipart/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).

  2. In case of a HTTP multipart/form-data request, the parameters are not available by HttpServletRequest#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, using HttpServletRequest#getParts(). You're already using Apache Commons FileUpload, so just keep that part and get rid of the unnecessary getParameter() calls. The regular parameters are available in the secion commented as "Process regular form fields here".

九厘米的零° 2024-11-06 03:22:00

拼写

检查您所做的

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

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

注意接收方缺少的 x-。

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.

滴情不沾 2024-11-06 03:22:00

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文