如何将图像加载到服务器使用POST,multipart / form-data(android)

时间:2015-09-02 13:26:32

标签: android post https multipartform-data

抱歉我的英文。今天我尝试在服务器使用后请求和multipart / form-data中加载图像。这对我来说非常重要。这是示例请求:

----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="image"; filename="imageName.jpeg"
Content-Type: image/jpeg

----WebKitFormBoundaryE19zNvXGzXaLvS5C

Bellow i create方法,将图像发送到服务器。但服务器说我:不,它的错误

public static String executeHttpLoadImage(String url, String nameValueF, String paramValueF, String nameValueS, String paramValueS,
                                                String filePath, String fileName) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = createHttpClient();

            HttpPost request = new HttpPost(); //post
            request.setURI(new URI(url));

            request.setHeader("Content-Type", "multipart/form-data"); //set header
            request.setHeader(nameValueF, paramValueF);               //set header
            request.setHeader(nameValueS, paramValueS);               //set header

            //set multipart
            MultipartEntity mpEntity = new MultipartEntity();        //multipart
            File file = new File(filePath);                          //file path
            ContentBody cbFile = new FileBody(file, "image/jpeg");   //body
            mpEntity.addPart(fileName, cbFile);                      //add

            request.setEntity(mpEntity);
            //set multipart

            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

0 个答案:

没有答案