如何上传Android的多部分表单数据和图像服务器?表单、图像、上传、部分

2023-09-06 13:44:14 作者:流浪者

状态code 500在上传多部分实体的图像在android的code服务器

HTML表单: (可以添加成功图像服务器)

 <形式方法=邮报行动=HTTP:// XYZ / upload_pictureENCTYPE =的multipart / form-data的>

      样品图片上传表单提交

      < BR />< BR />

      API密钥:<输入类型=文本名称=键值=ABC>< BR />< BR />
      登录:LT;输入类型=文本名称=登陆值=文本>< BR />
      密码:<输入类型=密码NAME =密码值=文本>< BR />< BR />

      物业编号:LT;输入类型=文本名称=property_id值=111>< BR />
      图片文件:其中;输入类型=文件NAME =图片>< BR />< BR />

      < BR />< BR />
      <输入类型=提交名称=值=上传图片>< BR />

    < /形式GT;
 

的Andr​​oid code: (给状态code 500)

  HttpClient的HttpClient的=新DefaultHttpClient();
            HttpPost httppost =新HttpPost(
                    HTTP:// XYZ / upload_picture);

            尝试 {
                MultipartEntity实体=新MultipartEntity();

                entity.addPart(钥匙,新StringBody(ABC));
                entity.addPart(登陆,新StringBody(ABC));
                entity.addPart(密码,新StringBody(测试));
                entity.addPart(property_id,新StringBody(111));


                档案文件=新的文件(Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_DCIM)的ToString()
                        +/Camera/Test.jpg);
                entity.addPart(图片报,新FileBody(文件));

                httppost.setEntity(实体);
                HTT presponse响应= httpclient.execute(httppost);

                Log.e(测试,SC+ response.getStatusLine()的getStatus code());

                HttpEntity resEntity = response.getEntity();

                的BufferedReader读卡器=新的BufferedReader(新的InputStreamReader(
                        。response.getEntity()的getContent(),UTF-8));
                字符串sResponse;
                StringBuilder的S =新的StringBuilder();

                而((sResponse = reader.readLine())!= NULL){
                    S = s.append(sResponse);
                }
                Log.e(测试,回应:+ S);
}赶上(ClientProtocolException E){
        }赶上(IOException异常E){
        }
 

解决方案 如何使用表单上传图片文件

如果你像我一样是用多部分上传挣扎。下面是使用95%的code从这个的Andr​​oid的代码片段的解决方案。

 公共字符串multipartRequest(字符串urlTo,地图<字符串,字符串> parmas,文件路径字符串,字符串的FileField,字符串fileMimeType)抛出CustomException {
        HttpURLConnection的连接= NULL;
        DataOutputStream类的OutputStream = NULL;
        的InputStream的InputStream = NULL;

        串twoHyphens = - ;
        字符串边界=*****+ Long.toString(System.currentTimeMillis的())+*****;
        字符串lineEnd =\ r \ N的;

        字符串结果=;

        INT读取动作,方bytesAvailable,缓冲区大小;
        byte []的缓冲区;
        INT maxBufferSize = 1 * 1024 * 1024;

        的String [] Q = filepath.split(/);
        INT IDX = q.length  -  1;

        尝试 {
            档案文件=新的文件(文件路径);
            的FileInputStream的FileInputStream =新的FileInputStream(文件);

            网址URL =新的URL(urlTo);
            连接=(HttpURLConnection类)url.openConnection();

            connection.setDoInput(真正的);
            connection.setDoOutput(真正的);
            connection.setUseCaches(假);

            connection.setRequestMethod(POST);
            connection.setRequestProperty(连接,保持活动);
            connection.setRequestProperty(用户代理,Android的多部分HTTP客户端1.0);
            connection.setRequestProperty(内容类型,多部分/格式数据;边界=+界);

            的OutputStream =新DataOutputStream类(connection.getOutputStream());
            outputStream.writeBytes(twoHyphens +边界+ lineEnd);
            outputStream.writeBytes(内容处置:表格数据;名称= \+的FileField +\;文件名= \+ Q [IDX] +\+ lineEnd);
            outputStream.writeBytes(内容类型:+ fileMimeType + lineEnd);
            outputStream.writeBytes(内容传输编码:二进制+ lineEnd);

            outputStream.writeBytes(lineEnd);

            方bytesAvailable = fileInputStream.available();
            BUFFERSIZE = Math.min(方bytesAvailable,maxBufferSize);
            缓冲区=新的字节[BUFFERSIZE]

            读取动作= fileInputStream.read(缓冲液,0,BUFFERSIZE);
            而(读取动作大于0){
                outputStream.write(缓冲液,0,BUFFERSIZE);
                方bytesAvailable = fileInputStream.available();
                BUFFERSIZE = Math.min(方bytesAvailable,maxBufferSize);
                读取动作= fileInputStream.read(缓冲液,0,BUFFERSIZE);
            }

            outputStream.writeBytes(lineEnd);

            //上传POST数据
            迭代器<字符串> 。键= parmas.keySet()迭代();
            而(keys.hasNext()){
                字符串键= keys.next();
                字符串值= parmas.get(密钥);

                outputStream.writeBytes(twoHyphens +边界+ lineEnd);
                outputStream.writeBytes(内容处置:表格数据;名称= \+按键+\+ lineEnd);
                outputStream.writeBytes(内容类型:text / plain的+ lineEnd);
                outputStream.writeBytes(lineEnd);
                outputStream.writeBytes(值);
                outputStream.writeBytes(lineEnd);
            }

            outputStream.writeBytes(twoHyphens +边界+ twoHyphens + lineEnd);


            如果(200!= connection.getResponse code()){
                抛出新CustomException(无法上传code:+ connection.getResponse code()++ connection.getResponseMessage());
            }

            的InputStream = connection.getInputStream();

            结果= this.convertStreamToString(InputStream的);

            fileInputStream.close();
            inputStream.close();
            outputStream.flush();
            outputStream.close();

            返回结果;
        }赶上(例外五){
            logger.error(E);
            抛出新CustomException(E);
        }

    }

    私人字符串convertStreamToString(InputStream的是){
        的BufferedReader读卡器=新的BufferedReader(新InputStreamReader的(是));
        StringBuilder的SB =新的StringBuilder();

        串线= NULL;
        尝试 {
            而((行= reader.readLine())!= NULL){
                sb.append(线);
            }
        }赶上(IOException异常E){
            e.printStackTrace();
        } 最后 {
            尝试 {
                is.close();
            }赶上(IOException异常E){
                e.printStackTrace();
            }
        }
        返回sb.toString();
    }
 

调用code:

  //设置PARAMS
地图<字符串,字符串> PARAMS =新的HashMap<字符串,字符串>(2);
        params.put(富,散列);
        params.put(酒吧,标题);

字符串结果= multipartRequest(URL_UPLOAD_VIDEO,参数,可以pathToVideoFile,视频,视频/ MP4);
//下一个解析结果字符串
 

Status code 500 during upload multipart entity image to server in android code

Html form: (can add successfully image to server)

 <form method="post" action="http://xyz/upload_picture" enctype="multipart/form-data">

      Sample Picture Upload Form Submit

      <br/><br/>

      API key: <input type="text" name="key" value="abc"><br/><br/>
      Login: <input type="text" name="login" value="text"><br/>
      Password: <input type="password" name="password" value="text"><br/><br/>

      Property ID:<input type="text" name="property_id" value="111"><br/>
      Picture File:<input type="file" name="picture"><br/><br/>

      <br/><br/>
      <input type="submit" name="" value="Upload Picture"><br/>

    </form>

Android code : (gives status code 500)

   HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(
                    "http://xyz/upload_picture");

            try {
                MultipartEntity entity = new MultipartEntity();

                entity.addPart("key", new StringBody("abc"));
                entity.addPart("login", new StringBody("abc"));
                entity.addPart("password", new StringBody("test"));
                entity.addPart("property_id", new StringBody("111"));


                File file = new File(Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_DCIM).toString()
                        + "/Camera/Test.jpg");
                entity.addPart("picture", new FileBody(file));

                httppost.setEntity(entity);
                HttpResponse response = httpclient.execute(httppost);

                Log.e("test", "SC:" + response.getStatusLine().getStatusCode());

                HttpEntity resEntity = response.getEntity();

                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        response.getEntity().getContent(), "UTF-8"));
                String sResponse;
                StringBuilder s = new StringBuilder();

                while ((sResponse = reader.readLine()) != null) {
                    s = s.append(sResponse);
                }
                Log.e("test", "Response: " + s);
} catch (ClientProtocolException e) {
        } catch (IOException e) {
        }

解决方案

If like me you were struggling with multipart upload. Here's a solution using 95% of code from this Android snippet.

public String multipartRequest(String urlTo, Map<String, String> parmas, String filepath, String filefield, String fileMimeType) throws CustomException {
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        InputStream inputStream = null;

        String twoHyphens = "--";
        String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
        String lineEnd = "\r\n";

        String result = "";

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;

        String[] q = filepath.split("/");
        int idx = q.length - 1;

        try {
            File file = new File(filepath);
            FileInputStream fileInputStream = new FileInputStream(file);

            URL url = new URL(urlTo);
            connection = (HttpURLConnection) url.openConnection();

            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

            outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] + "\"" + lineEnd);
            outputStream.writeBytes("Content-Type: " + fileMimeType + lineEnd);
            outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);

            outputStream.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0) {
                outputStream.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

            outputStream.writeBytes(lineEnd);

            // Upload POST Data
            Iterator<String> keys = parmas.keySet().iterator();
            while (keys.hasNext()) {
                String key = keys.next();
                String value = parmas.get(key);

                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
                outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
                outputStream.writeBytes(lineEnd);
                outputStream.writeBytes(value);
                outputStream.writeBytes(lineEnd);
            }

            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);


            if (200 != connection.getResponseCode()) {
                throw new CustomException("Failed to upload code:" + connection.getResponseCode() + " " + connection.getResponseMessage());
            }

            inputStream = connection.getInputStream();

            result = this.convertStreamToString(inputStream);

            fileInputStream.close();
            inputStream.close();
            outputStream.flush();
            outputStream.close();

            return result;
        } catch (Exception e) {
            logger.error(e);
            throw new CustomException(e);
        }

    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

Calling code:

//setup params
Map<String, String> params = new HashMap<String, String>(2);
        params.put("foo", hash);
        params.put("bar", caption);

String result = multipartRequest(URL_UPLOAD_VIDEO, params, pathToVideoFile, "video", "video/mp4");
//next parse result string