android - 上传图像 HTTP POST Android

标签 android http-post

我是 android 的新手,在 android 中上传图片时遇到问题。我已经尝试找到示例但没有运气:

我说错了:

enter image description here

这是我的代码: 我有一个名为 "images" 的数组,其中包含我要上传的图像的路径 例如/storage/sdcard0/DCIM/Camera/IMG_20131214_171438.jpg

//ONCLICK LISTENER    
public OnClickListener upload_image = new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if(images.size() != 0) {

                    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                    StrictMode.setThreadPolicy(policy);

                    for(int i=0; i<images.size(); i++){
                        doFileUpload(images.get(i));
                    }
                }
            }
        };

//上传

private void doFileUpload(String upload_file){
                Log.d("Currently queued", upload_file);
                HttpURLConnection conn = null;
                DataOutputStream dos = null;
                DataInputStream inStream = null;
                String exsistingFileName = upload_file;
                // Is this the place are you doing something wrong.
                String lineEnd = "\r\n";
                String twoHyphens = "--";
                String boundary =  "acebdf13572468";
                int bytesRead, bytesAvailable, bufferSize;
                byte[] buffer;
                int maxBufferSize = 1*1024*1024;
                String urlString = "http://test.xponlm.com/MobileServices/api/ShipmentImages";
                try
                {
                    Log.e("MediaPlayer","Inside second Method");
                    FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );
                    URL url = new URL(urlString);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setDoInput(true);
                    // Allow Outputs
                    conn.setDoOutput(true);
                    // Don't use a cached copy.
                    conn.setUseCaches(false);
                    // Use a post method.
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Connection", "Keep-Alive");
                    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
                    dos = new DataOutputStream( conn.getOutputStream() );
                    dos.writeBytes(twoHyphens + boundary + lineEnd);
                    dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + exsistingFileName +"\"" + lineEnd);
                    dos.writeBytes(lineEnd);

                    dos.writeBytes(twoHyphens + boundary + lineEnd);
                    dos.writeBytes("Content-Disposition: form-data; name=\"ID\""+ lineEnd);
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(strshipmentID + lineEnd);

                    dos.writeBytes(twoHyphens + boundary + lineEnd);
                    dos.writeBytes("Content-Disposition: form-data; name=\"ImageType\""+ lineEnd);
                    dos.writeBytes(lineEnd);
                    dos.writeBytes("JPG" + lineEnd);

                    dos.writeBytes(twoHyphens + boundary + lineEnd);
                    dos.writeBytes("Content-Disposition: form-data; name=\"FileType\""+ lineEnd);
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(strtype + lineEnd);

                    Log.e("MediaPlayer","Headers are written");
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    buffer = new byte[bufferSize];
                    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);
                    }

                    dos.writeBytes(lineEnd);
                    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String inputLine;
                    while ((inputLine = in.readLine()) != null)
//                      tv.append(inputLine);
                        Log.d("inputLine", inputLine);
                    // close streams
                    Log.e("MediaPlayer","File is written");
                    fileInputStream.close();
                    dos.flush();
                    dos.close();
                }
                catch (MalformedURLException ex)
                {
                    Log.e("MediaPlayer", "error1: " + ex.getMessage(), ex);
                }
                catch (IOException ioe)
                {
                    Log.e("MediaPlayer", "error2: " + ioe.getMessage(), ioe);
                }

                //------------------ read the SERVER RESPONSE
                try {
                    inStream = new DataInputStream ( conn.getInputStream() );
                    String str;            

                    while (( str = inStream.readLine()) != null) {
                        Log.e("MediaPlayer","Server Response"+str);
                    }
                    /*while((str = inStream.readLine()) !=null ){

                    }*/
                    inStream.close();
                }
                catch (IOException ioex){
                    Log.e("MediaPlayer", "error3: " + ioex.getMessage(), ioex);
                }
            }

我错过了什么吗?你能说出我的代码有什么问题吗?

最佳答案

public Fileupload(String url, String userid,
            String filepath, String status) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        MultipartEntity entity = new MultipartEntity(
                HttpMultipartMode.BROWSER_COMPATIBLE);
        HttpParams httpParams = httpclient.getParams();
        httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 100000);
        try {
            entity.addPart("key 1",
                    new StringBody(userid, Charset.forName("UTF-8")));
            entity.addPart("key 2",
                    new StringBody(status, Charset.forName("UTF-8")));
            entity.addPart("File ", new FileBody(new File(filepath)));
            httppost.setEntity(entity);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String response = httpclient.execute(httppost, responseHandler);

        } catch (Exception e) {

        }
    }

关于android - 上传图像 HTTP POST Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21275208/

相关文章:

android - 从 Android 获取 Google oauth 授权 token -返回无效范围/未知错误

php - 通过 php/android 在排序的 mySQL 表中的正确位置插入数据

php - jquery post与$.ajax,如何避免多次发布?

javascript - AngularJS/Rails $http.post 数据字段名称作为变量

java - Android 客户端-服务器应用程序 - readLine() 不起作用

java - 空指针异常 - 我没有初始化什么?

java - 传递 fragment 的上下文

android - 通过 thread_id 取得联系

javascript - 禁用带有字符白名单的表单提交

c# - 以编程方式篡改 http 请求