如何从GALLARY上传图片到服务器? [英] How to upload image from gallary to server?

查看:239
本文介绍了如何从GALLARY上传图片到服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的画廊浏览图片,并试图在服务器发送和下面这个教程<一个href=\"http://androidexample.com/Upload_File_To_Server_-_Android_Example/index.php?view=article_discription&aid=83&aaid=106\" rel=\"nofollow\">http://androidexample.com/Upload_File_To_Server_-_Android_Example/index.php?view=article_discription&aid=83&aaid=106使用JSON但每当我试图把它上传显示文件上传全成,但是当我点击浏览按钮我GALLARY显示什么都没有,所以我需要首先从画廊浏览,并显示在我的ImageView的图像,然后上传successfullcan任何机构告诉我是什么问题呢?



UploadToServer:

 公共类UploadToServer延伸活动{
TextView中MessageText中;
按钮uploadButton;
INT serverResponse code = 0;
ProgressDialog对话框= NULL;
字符串upLoadServerUri = NULL;/********** 文件路径 *************/
最后弦乐uploadFilePath =到/ mnt / SD卡/图片/;
最后弦乐uploadFileName =service_lifecycle.png;
私有静态诠释RESULT_LOAD_IMAGE = 1;
@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_upload_to_server);
    ImageView的buttonLoadImage =(ImageView的)findViewById(R.id.buttonLoadPicture);
    buttonLoadImage.setOnClickListener(新View.OnClickListener(){        @覆盖
        公共无效的onClick(查看为arg0){            意图I =新意图(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);            startActivityForResult(ⅰ,RESULT_LOAD_IMAGE);
        }
    });
    uploadButton =(按钮)findViewById(R.id.uploadButton);
    MessageText中=(的TextView)findViewById(R.id.messageText);    messageText.setText(上传文件路径: - 到/ mnt / SD卡/图片/+ uploadFileName);    / ************* PHP脚本路径**************** /
    upLoadServerUri =htt​​p://www.androidexample.com/media/Uplo​​adToServer.php;    uploadButton.setOnClickListener(新OnClickListener(){
        @覆盖
        公共无效的onClick(视图v){            对话框= ProgressDialog.show(UploadToServer.this,,上传文件...,真正的);            新主题(新的Runnable接口(){
                    公共无效的run(){
                         runOnUiThread(新的Runnable(){
                                公共无效的run(){
                                    messageText.setText(上传开始......);
                                }
                            });                         uploadFile(uploadFilePath ++ uploadFileName);                    }
                  })。开始();
            }
        });
}
@覆盖
保护无效的onActivityResult(INT申请code,INT结果code,意图数据){
    // TODO自动生成方法存根
    如果(要求code == RESULT_LOAD_IMAGE&放大器;&安培;结果code == RESULT_OK&放大器;&安培;!NULL =数据){
        乌里selectedImageUri = data.getData();
        字符串TEMPPATH =的getPath(selectedImageUri,这一点);        //添加此        ImageView的ImageView的=(ImageView的)findViewById(R.id.imgView);
        imageView.setImageBitmap(BitmapFactory.de codeFILE(TEMPPATH));
    }
}
私人字符串的getPath(URI URI,UploadToServer uploadToServer){
    如果(URI == NULL){
        返回null;
    }
    的String [] =投影{MediaStore.Images.Media.DATA};
    光标光标= getContentResolver()查询(URI,投影,NULL,NULL,NULL);
    如果(指针!= NULL){
        INT与Column_Index =光标
        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        返回cursor.getString(Column_Index中);
    }
    返回uri.getPath();
}
公众诠释uploadFile(字符串sourceFileUri){
      字符串文件名= sourceFileUri;      HttpURLConnection的康恩= NULL;
      DataOutputStream类DOS = NULL;
      字符串lineEnd =\\ r \\ n;
      串twoHyphens = - ;
      字符串边界=*****;
      INT读取动作,方bytesAvailable,缓冲区大小;
      字节[]缓冲区;
      INT MAXBUFFERSIZE = 1 * 1024 * 1024;
      文件的资源文件=新的文件(sourceFileUri);      如果(!sourceFile.isFile()){           dialog.dismiss();           Log.e(一个UploadFile,源文件不存在
                               + uploadFilePath ++ uploadFileName);           runOnUiThread(新的Runnable(){
               公共无效的run(){
                   messageText.setText(源文件不存在
                           + uploadFilePath ++ uploadFileName);
               }
           });           返回0;      }
      其他
      {
           尝试{                 //打开一个URL连接到这个Servlet
               的FileInputStream的FileInputStream =新的FileInputStream(的资源文件);
               网址URL =新的URL(upLoadServerUri);               //打开HTTP连接的URL
               康恩=(HttpURLConnection类)url.openConnection();
               conn.setDoInput(真); //允许输入
               conn.setDoOutput(真); //允许输出
               conn.setUseCaches(假); //不要使用缓存副本
               conn.setRequestMethod(POST);
               conn.setRequestProperty(连接,保持活动);
               conn.setRequestProperty(ENCTYPE,多部分/表单数据);
               conn.setRequestProperty(内容类型,的multipart / form-data的;边界=+边界);
               conn.setRequestProperty(uploaded_file,文件名);               DOS =新的DataOutputStream类(conn.getOutputStream());               dos.writeBytes(twoHyphens +边界+ lineEnd);
               dos.writeBytes(内容处置:表格数据;名称= \\uploaded_file \\;文件名= \\
                                         +文件名+\\+ lineEnd);               dos.writeBytes(lineEnd);               //创建最大大小的缓冲区
               参考bytesAvailable = fileInputStream.available();               BUFFERSIZE = Math.min(方bytesAvailable,MAXBUFFERSIZE);
               缓冲区=新的字节[缓冲区大小]               //读取文件,并将其写入形式...
               读取动作= fileInputStream.read(缓冲液,0,缓冲区大小);               而(读取动作大于0){                 dos.write(缓冲液,0,缓冲区大小);
                 参考bytesAvailable = fileInputStream.available();
                 BUFFERSIZE = Math.min(方bytesAvailable,MAXBUFFERSIZE);
                 读取动作= fileInputStream.read(缓冲液,0,缓冲区大小);                }               //发送文件数据后necesssary多部分的表单数据...
               dos.writeBytes(lineEnd);
               dos.writeBytes(twoHyphens +边界+ twoHyphens + lineEnd);               //服务器的响应(code和消息)
               serverResponse code = conn.getResponse code();
               串serverResponseMessage = conn.getResponseMessage();               Log.i(一个UploadFile,HTTP响应是:
                       + serverResponseMessage +:+ serverResponse code);               如果(serverResponse code == 200){                   runOnUiThread(新的Runnable(){
                        公共无效的run(){                            弦乐味精=文件上传完成\\ n \\ n看到这里上传的文件:\\ n \\ n
                                          +http://www.androidexample.com/media/uploads/
                                          + uploadFileName;                            messageText.setText(MSG);
                            Toast.makeText(UploadToServer.this,文件上传完成。
                                         Toast.LENGTH_SHORT).show();
                        }
                    });
               }               //关闭流//
               fileInputStream.close();
               dos.flush();
               dos.close();          }赶上(MalformedURLException的前){              dialog.dismiss();
              ex.printStackTrace();              runOnUiThread(新的Runnable(){
                  公共无效的run(){
                      messageText.setText(MalformedURLException的例外情况:检查脚本网址。);
                      Toast.makeText(UploadToServer.thisMalformedURLException的,Toast.LENGTH_SHORT).show();
                  }
              });              Log.e(上传文件到服务器,错误:+ ex.getMessage(),除息);
          }赶上(例外五){              dialog.dismiss();
              e.printStackTrace();              runOnUiThread(新的Runnable(){
                  公共无效的run(){
                      messageText.setText(得到例外:看到logcat的);
                      Toast.makeText(UploadToServer.this,得到了异常:看到logcat的
                              Toast.LENGTH_SHORT).show();
                  }
              });
              Log.e(上传文件到服务器异常,异常
                                               + e.getMessage(),E);
          }
          dialog.dismiss();
          返回serverResponse code;       } //结束else块
     }
  }


解决方案

您可以使用多图片上传这样的。


  1. 创建的AsyncTask

ArrayList的productFiles =新的ArrayList();

 类UploadImageTask扩展的AsyncTask&LT;字符串,整数,字符串&GT;
{
    ProgressDialog对话框;
    @覆盖
    保护字符串doInBackground(字符串... PARAMS)
    {
        INT isCover = 0;
        串gal_image =;
        的for(int i = 0; I&LT; productFiles.size();我++)
        {
            如果(我== 0)
                isCover = 1;
            其他
                isCover = 0;
            publishProgress第(i + 1);
            字符串s = HelperHttp.uploadFile(productFiles.get(ⅰ),
                    Constants.BASE_URL +send_image.php,则params [0],
                    isCover +);
            尝试{
                JSONObject的工作=新的JSONObject(S);
                如果(job.optInt(身份)== 1){
                    Helper.Log(上传成功,I +完成);
                    如果(gal_image.equals())
                        gal_image = job.optString(gal_image);
                }
            }赶上(JSONException E){
                e.printStackTrace();
            }
        }
        返回gal_image;
    }@覆盖
在preExecute保护无效(){
    super.on preExecute();
    对话框= DialogManager.getProgressDialog(SellActivity.this);
    dialog.setMessage(上传1+ productFiles.size()+图像(S));
}@覆盖
保护无效onPostExecute(最后弦乐结果){
    super.onPostExecute(结果);
    dialog.dismiss();
        }

}

2。
与方法上传文件如下创建Helper类

 公共静态字符串uploadFile(档案文件,URL字符串,字符串的productId,字符串isCover)
    {
        StringBuffer的数据=新的StringBuffer();
        HttpPost httpost =新HttpPost(URL);
        Helper.Log(上传文件,网址);
        MultipartEntity实体=新MultipartEntity();
        entity.addPart(一个UploadFile,新FileBody(文件));
        尝试
        {
            entity.addPart(txtProductId,新StringBody(productId参数));
        }
        赶上(UnsupportedEncodingException E1)
        {
            e1.printStackTrace();
        }
        httpost.setEntity(实体);
        HTT presponse响应;
        尝试{
            响应= getThreadSafeClient()执行(httpost)。
            HttpEntity ENTITY2 = response.getEntity();
            InputStream为= entity2.getContent();
            读者的BufferedReader =新的BufferedReader(新的InputStreamReader(是),8192);
            串线= NULL;
            而((行= reader.readLine())!= NULL)
            {
                data.append(线);
            }
            。response.getEntity()consumeContent();
            Helper.Log(回应==&gt;中,data.toString()+);
            返回data.toString();
        }赶上(ClientProtocolException E){
            e.printStackTrace();
        }赶上(IOException异常五){
            e.printStackTrace();
        }
        返回;
    }

您还可以添加参数的要求。
要添加参数,使用以下code

  entity.addPart(钥匙,值);

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

这篇关于如何从GALLARY上传图片到服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆