如何将图像从库上传到服务器?

时间:2014-12-18 05:46:17

标签: android json image-uploading

我正在尝试从我的图库中浏览图片并尝试在服务器中发送它并使用json跟随本教程http://androidexample.com/Upload_File_To_Server_-_Android_Example/index.php?view=article_discription&aid=83&aaid=106但是每当我尝试上传它时显示文件已成功上传,但是当我点击浏览按钮时我的gallary显示什么都没有,所以我需要首先从图库浏览并在我的imageview中显示该图像,然后上传成功任何身体告诉我什么是问题?

enter image description here enter image description here UploadToServer:

 public class UploadToServer extends Activity {
TextView messageText;
Button uploadButton;
int serverResponseCode = 0;
ProgressDialog dialog = null;
String upLoadServerUri = null;

/**********  File Path *************/
final String uploadFilePath = "/mnt/sdcard/Pictures/";
final String uploadFileName = "service_lifecycle.png";
private static int RESULT_LOAD_IMAGE = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload_to_server);
    ImageView buttonLoadImage = (ImageView) findViewById(R.id.buttonLoadPicture);
    buttonLoadImage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent i = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(i, RESULT_LOAD_IMAGE);
        }
    });
    uploadButton = (Button)findViewById(R.id.uploadButton);
    messageText  = (TextView)findViewById(R.id.messageText);

    messageText.setText("Uploading file path :- '/mnt/sdcard/Pictures/"+uploadFileName);

    /************* Php script path ****************/
    upLoadServerUri = "http://www.androidexample.com/media/UploadToServer.php";

    uploadButton.setOnClickListener(new OnClickListener() {            
        @Override
        public void onClick(View v) {

            dialog = ProgressDialog.show(UploadToServer.this, "", "Uploading file...", true);

            new Thread(new Runnable() {
                    public void run() {
                         runOnUiThread(new Runnable() {
                                public void run() {
                                    messageText.setText("uploading started.....");
                                }
                            });                      

                         uploadFile(uploadFilePath + "" + uploadFileName);

                    }
                  }).start();        
            }
        });
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImageUri = data.getData();  
        String tempPath = getPath(selectedImageUri, this);

        //add this

        ImageView imageView = (ImageView) findViewById(R.id.imgView);
        imageView.setImageBitmap(BitmapFactory.decodeFile(tempPath ));
    }
}


private String getPath(Uri uri, UploadToServer uploadToServer) {
    if( uri == null ) {
        return null;
    }
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
    if( cursor != null ){
        int column_index = cursor
        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
    return uri.getPath();
}


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

3 个答案:

答案 0 :(得分:0)

您应该尝试更新uploadFilePath变量。首先使用Environment.getExternalStoragePublicDirectory()获取顶级外部存储目录,然后添加图像的相对路径以访问要上载的文件。以下是文档:http://developer.android.com/reference/android/os/Environment.html#getExternalStoragePublicDirectory(java.lang.String)

答案 1 :(得分:0)

您可以像这样使用多部分图片上传。

  1. 创建AsyncTask
  2. ArrayList productFiles = new ArrayList();

    class UploadImageTask extends AsyncTask<String, Integer, String> 
    {
        ProgressDialog dialog;
        @Override
        protected String doInBackground(String... params) 
        {
            int isCover = 0;
            String gal_image = "";
            for (int i = 0; i < productFiles.size(); i++) 
            {
                if (i == 0) 
                    isCover = 1;
                else 
                    isCover = 0;
                publishProgress(i + 1);
                String s = HelperHttp.uploadFile(productFiles.get(i),
                        Constants.BASE_URL + "send_image.php", params[0],
                        isCover + "");
                try {
                    JSONObject job = new JSONObject(s);
                    if (job.optInt("status") == 1) {
                        Helper.Log("Upload success", i + " done");
                        if (gal_image.equals(""))
                            gal_image = job.optString("gal_image");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            return gal_image;
        }
    
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = DialogManager.getProgressDialog(SellActivity.this);
        dialog.setMessage("uploading 1 of " + productFiles.size()+ " image(s)");
    }
    
    @Override
    protected void onPostExecute(final String result) {
        super.onPostExecute(result);
        dialog.dismiss();
            }
    

    }

    2。 使用方法上传文件创建Helper类,如下所示

    public static String uploadFile(File file, String url, String productId,String isCover) 
        {
            StringBuffer data = new StringBuffer();
            HttpPost httpost = new HttpPost(url);
            Helper.Log("Upload file", url);
            MultipartEntity entity = new MultipartEntity();
            entity.addPart("uploadfile", new FileBody(file));
            try 
            {
                entity.addPart("txtProductId", new StringBody(productId));
            } 
            catch (UnsupportedEncodingException e1) 
            {
                e1.printStackTrace();
            }
            httpost.setEntity(entity);
            HttpResponse response;
            try {
                response = getThreadSafeClient().execute(httpost);
                HttpEntity entity2 = response.getEntity();
                InputStream is = entity2.getContent();
                BufferedReader reader = new BufferedReader( new InputStreamReader(is), 8192);
                String line = null;
                while ((line = reader.readLine()) != null) 
                {
                    data.append(line);
                }
                response.getEntity().consumeContent();
                Helper.Log("Response==>", data.toString() + "");
                return data.toString();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "";
        }
    

    您还可以添加参数以进行请求。 要在代码

    之后添加参数
    entity.addPart("Key", value);
    

答案 2 :(得分:-1)

将图像转换为位图

ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);

将encodedImage作为字符串发送到服务器,在服务器级解码以获取字符串