Android上传图片到服务器?

时间:2014-05-27 10:39:40

标签: android web-services

您好每个人都请帮助我,我正在尝试使用此代码上传图片和文字,但它不适合我任何解决方案

 HttpURLConnection conn = null;
            DataOutputStream dos = null;
            InputStream inStream = null;
            String lineEnd = "rn";
            String twoHyphens = "--";
            String boundary =  "*****";
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1*1024*1024;
            String responseFromServer = "";
            String urlString = webserviceURLs.createQuestion;
            try
            {
             //------------------ CLIENT REQUEST
            FileInputStream fileInputStream = new FileInputStream(new File(imageName.get(0)) );
             // open a URL connection to the Servlet
             URL url = new URL(urlString);
             // Open a HTTP connection to the URL
             conn = (HttpURLConnection) url.openConnection();
             // Allow Inputs
             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:attachment; name=\"userquestion[looks][0][photo]\";filename=" + imageName.get(0) + "" + lineEnd);
             dos.writeBytes(lineEnd);
             // create a buffer of maximum size
             bytesAvailable = fileInputStream.available();
             bufferSize = Math.min(bytesAvailable, 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);
             // close streams
             Log.e("Debug","File is written");
             fileInputStream.close();
             dos.flush();
             dos.close();
            }
            catch (MalformedURLException ex)
            {
                 Log.e("Debug", "error: " + ex.getMessage(), ex);
            }
            catch (IOException ioe)
            {
                 Log.e("Debug", "error: " + ioe.getMessage(), ioe);
            }
            //------------------ read the SERVER RESPONSE
            try {
                  inStream =   conn.getInputStream() ;
                  String str;

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

            }
            catch (IOException ioex){
                 Log.e("Debug", "error: " + ioex.getMessage(), ioex);
            }
            return urlString;
          }

这是我的代码,我在服务中有两个参数" userquestion [question_id]"和" userquestion [长相] [0] [照片]"一个用于文本,另一个用于图像,请告诉我如何使用此代码保存此内容

这是我的logcat

05-27 10:26:53.547: E/Debug(5500): error: http://staging.com/api/userquestions.json
05-27 10:26:53.547: E/Debug(5500): java.io.FileNotFoundException: http://staging.com/api/userquestions.json
05-27 10:26:53.547: E/Debug(5500):  at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)
05-27 10:26:53.547: E/Debug(5500):  at com.Okay.Webservices.Service_CreateQuestion.doInBackground(Service_CreateQuestion.java:118)
05-27 10:26:53.547: E/Debug(5500):  at com.Okay.Webservices.Service_CreateQuestion.doInBackground(Service_CreateQuestion.java:1)
05-27 10:26:53.547: E/Debug(5500):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
05-27 10:26:53.547: E/Debug(5500):  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
05-27 10:26:53.547: E/Debug(5500):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
05-27 10:26:53.547: E/Debug(5500):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
05-27 10:26:53.547: E/Debug(5500):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
05-27 10:26:53.547: E/Debug(5500):  at java.lang.Thread.run(Thread.java:841)

3 个答案:

答案 0 :(得分:0)

使用此代码..

  Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.annag);    

    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bm.compress(CompressFormat.JPEG, 75, bos);
        byte[] data = bos.toByteArray();
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(url_path);
        ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
        // File file= new File("/mnt/sdcard/forest.png");
        // FileBody bin = new FileBody(file);
        MultipartEntity reqEntity = new MultipartEntity(
                HttpMultipartMode.BROWSER_COMPATIBLE);

        reqEntity.addPart("store_name", new StringBody("amazon"));
        reqEntity.addPart("file", bab);
        postRequest.setEntity(reqEntity);

        HttpResponse response = httpClient.execute(postRequest);

        String my_response = convertStreamToString(response.getEntity()
                .getContent());
        Toast.makeText(getApplicationContext(), my_response,
                Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

答案 1 :(得分:0)

试试这个:

Android方面:

 public int uploadFile(String sourceFileUri) {


          String fileName = sourceFileUri;

          HttpURLConnection conn = null;
          DataOutputStream dos = null;  
          String lineEnd = "\r\n";
          String twoHyphens = "--";
          String boundary = "*****";
          int bytesRead, bytesAvailable, bufferSize;
          byte[] buffer;
          int maxBufferSize = 1 * 1024 * 1024; 
          File sourceFile = new File(sourceFileUri); 

          if (!sourceFile.isFile()) {

               dialog.dismiss(); 

               Log.e("uploadFile", "Source File not exist :"
                                   +uploadFilePath + "" + uploadFileName);

               runOnUiThread(new Runnable() {
                   public void run() {
                       messageText.setText("Source File not exist :"
                               +uploadFilePath + "" + uploadFileName);
                   }
               }); 

               return 0;

          }
          else
          {
               try { 

                     // open a URL connection to the Servlet
                   FileInputStream fileInputStream = new FileInputStream(sourceFile);
                   URL url = new URL(upLoadServerUri);

                   // Open a HTTP  connection to  the URL
                   conn = (HttpURLConnection) url.openConnection(); 
                   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("ENCTYPE", "multipart/form-data");
                   conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                   conn.setRequestProperty("uploaded_file", fileName); 

                   dos = new DataOutputStream(conn.getOutputStream());

                   dos.writeBytes(twoHyphens + boundary + lineEnd); 
                   dos.writeBytes("Content-Disposition: form-data; name="uploaded_file";filename=""
                                             + fileName + """ + lineEnd);

                   dos.writeBytes(lineEnd);

                   // create a buffer of  maximum size
                   bytesAvailable = fileInputStream.available(); 

                   bufferSize = Math.min(bytesAvailable, 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();

                   Log.i("uploadFile", "HTTP Response is : "
                           + serverResponseMessage + ": " + serverResponseCode);

                   if(serverResponseCode == 200){

                       runOnUiThread(new Runnable() {
                            public void run() {

                                String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                              +" http://www.androidexample.com/media/uploads/"
                                              +uploadFileName;

                                messageText.setText(msg);
                                Toast.makeText(UploadToServer.this, "File Upload Complete.", 
                                             Toast.LENGTH_SHORT).show();
                            }
                        });                
                   }    

                   //close the streams //
                   fileInputStream.close();
                   dos.flush();
                   dos.close();

              } catch (MalformedURLException ex) {

                  dialog.dismiss();  
                  ex.printStackTrace();

                  runOnUiThread(new Runnable() {
                      public void run() {
                          messageText.setText("MalformedURLException Exception : check script url.");
                          Toast.makeText(UploadToServer.this, "MalformedURLException", 
                                                              Toast.LENGTH_SHORT).show();
                      }
                  });

                  Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
              } catch (Exception e) {

                  dialog.dismiss();  
                  e.printStackTrace();

                  runOnUiThread(new Runnable() {
                      public void run() {
                          messageText.setText("Got Exception : see logcat ");
                          Toast.makeText(UploadToServer.this, "Got Exception : see logcat ", 
                                  Toast.LENGTH_SHORT).show();
                      }
                  });
                  Log.e("Upload file to server Exception", "Exception : "
                                                   + e.getMessage(), e);  
              }
              dialog.dismiss();       
              return serverResponseCode; 

           } // End else block 
         } 
}

php:

<?php

    $file_path = "uploads/";

    $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
        echo "success";
    } else{
        echo "fail";
    }
 ?>

Source

答案 2 :(得分:0)

 Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
 ByteArrayOutputStream stream = new ByteArrayOutputStream();
 bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
 byte[] byte_arr = stream.toByteArray();
 String image_str = Base64.encodeBytes(byte_arr);
 ArrayList <NameValuePair> nameValuePairs = new ArrayList <NameValuePair> ();

 nameValuePairs.add(new BasicNameValuePair("image", image_str));

 Thread t = new Thread(new Runnable() {

    @Override
    public void run() {
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://10.0.2.2/Upload_image_ANDROID/upload_image.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            String the_string_response = convertResponseToString(response);
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Toast.makeText(UploadImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
                }
            });

        } catch (Exception e) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Toast.makeText(UploadImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            });
            System.out.println("Error in http connection " + e.toString());
        }
    }
 });
 t.start();
 }

 public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException {

    String res = "";
    StringBuffer buffer = new StringBuffer();
    inputStream = response.getEntity().getContent();
    int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            Toast.makeText(UploadImage.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();
        }
    });

    if (contentLength < 0) {} else {
        byte[] data = new byte[512];
        int len = 0;
        try {
            while (-1 != (len = inputStream.read(data))) {
                buffer.append(new String(data, 0, len)); //converting to string and appending  to stringbuffer…..
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            inputStream.close(); // closing the stream…..
        } catch (IOException e) {
            e.printStackTrace();
        }
        res = buffer.toString(); // converting stringbuffer to string…..

        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(UploadImage.this, "Result : " + res, Toast.LENGTH_LONG).show();
            }
        });
        //System.out.println("Response => " +  EntityUtils.toString(response.getEntity()));
    }
    return res;
 }
 }