简体   繁体   中英

How to upload image from gallary to server?

I am trying to browse image from my gallery and trying to send it in server and following this tutorial http://androidexample.com/Upload_File_To_Server_-_Android_Example/index.php?view=article_discription&aid=83&aaid=106 using json but whenever I am trying to upload it shows file uploaded successfull,but when i click on browse button my gallary display nothing,so i need to first browse from gallery and show that image in my imageview and then upload successfullcan any body tell me what is problem?

在此处输入图片说明在此处输入图片说明 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 
     } 
  }

You should try updating your uploadFilePath variable. Get the top level external storage directory first by using Environment.getExternalStoragePublicDirectory() and then suffix the relative path to your image to access the file for uploading. Here is the documentation: http://developer.android.com/reference/android/os/Environment.html#getExternalStoragePublicDirectory(java.lang.String)

You can use multipart image upload like this.

  1. create AsyncTask

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. Create Helper class with method upload file as follow

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

You can also add parameter to request. To add parameter use following code

entity.addPart("Key", value);

Convert the image to bitmap

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

Send the encodedImage to server as string, decode it at the server level to get the string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM