send parameters while uploading file

来源:互联网 发布:木村拓哉女儿 知乎 编辑:程序博客网 时间:2024/05/22 07:42


send parameters while uploading file

up vote0down votefavorite
1

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

3 Answers

activeoldestvotes
up vote4down voteaccepted

There are two major problems:

  1. The URLConnection#setRequestProperty() sets the HTTP request header, not the HTTP requestparameter. 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".

0 0
原创粉丝点击