Httpclient使用multipart / form-data进行POST

时间:2011-04-04 04:36:20

标签: java android servlets

我需要上传图片。为此,我必须通过图像&服务器的ID:

dos.writeBytes("Content-Disposition: form-data; name=\"file_name\";filename=\""
            + fileName + "\"" + lineEnd);


        dos.writeBytes("Content-Disposition: form-data; name=\"" + stringFieldName + "\""+ lineEnd);
        dos.writeBytes(lineEnd);

fileName是图像路径 stringFieldName是user_id

我的代码如下:

 public void webservicePhp(Long userId, Bitmap bmp) {

        String userIdParameter = String.valueOf(userId);
        String fileName = "temporary_holder.jpg";
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;

        String charset = "UTF-8";
        String responseFromServer = "";


        String stringFieldName = "user_id";


        String sourceFileUri = HomeScreen.get_path();
        String upLoadServerUri = "http://10.120.10.87:8080/ContactsManagerWeb/UploadImage";

        File sourceFile = new File(sourceFileUri);
        if (!sourceFile.isFile()) {
            Log.e("Huzza", "Source File Does not exist");
            return;
        }
        int serverResponseCode = 0;
        try { // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(sourceFile);





            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("Accept-Charset", charset);

            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type",
                "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("file_name", fileName);
            conn.setRequestProperty("user_id", userIdParameter);
                    dos = new DataOutputStream(conn.getOutputStream());
            dos.write(query.getBytes(charset));
            dos.writeBytes(twoHyphens + boundary + lineEnd);

            dos.writeBytes("Content-Disposition: form-data; name=\"file_name\";filename=\""
                + fileName + "\"" + lineEnd);


            dos.writeBytes("Content-Disposition: form-data; name=\"" + stringFieldName + "\""+ lineEnd);
            dos.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available(); // create a buffer of
                                  // maximum size
                bufferSize = (int) sourceFile.length();

            System.out.println("BytesAvail" + bytesAvailable);
            System.out.println("maxBufferSize" + maxBufferSize);
            buffer = new byte[bufferSize];

            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);

            bytesAvailable = fileInputStream.available();

            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();

            System.out.println("Upload file to serverHTTP Response is : "
                + serverResponseMessage + ": " + serverResponseCode);
            // close streams
            System.out.println("Upload file to server"+ fileName + " File is written");
            fileInputStream.close();
            dos.flush();
            dos.close();
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // this block will give the response of upload link
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
            System.out.println("RESULT Message: " + line);
            }
            rd.close();
        } catch (IOException ioex) {
            Log.e("Huzza", "error: " + ioex.getMessage(), ioex);
        }
        return; // like 200 (Ok)

        }

    }

在我的servlet中,我无法访问user_id参数。它没有到达那里

Servlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();    

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


                    //File file = new File("C:\\", 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();
                }

            }
        }
        // Show result page.


        System.out.println("request"+request.getAttribute("image"));
        //response.setContentType("image/jpeg"); 
        request.setAttribute("servletName", filenameImg);



        getServletConfig().getServletContext().getRequestDispatcher(
        "/result.jsp").forward(request,response);

        }



if (item.isFormField()) {} is retuned as false : 

请帮助

1 个答案:

答案 0 :(得分:2)

如果这与html表单提交相同。然后你可以试试这个。

在Servlet的if (item.isFormField()) {中执行此操作。

String user_Id = null; //Create an instance of String variable before initializing (Optional)

if (item.isFormField()) {
    if(item.getFieldName().contentEquals("name")){  //Check if the item in the loop is the user_id
         user_id = item.getString();                //If yes store the value
    }
} else { //continue with your current code

之前我遇到了同样的问题,这是我的工作。我不确定你是否正在寻找,只是试一试。