上传图片HTTP POST Android

时间:2014-01-22 05:49:56

标签: 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));
                    }
                }
            }
        };

// UPLOAD

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

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

1 个答案:

答案 0 :(得分:1)

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

        }
    }