dongzang5815 2014-08-26 06:16
浏览 78
已采纳

将图像从android sd卡上传到php服务器

I'm trying to upload image file from sdcard to php server. So while uploading i got internal server error 500. I had created uploads folder in server also. But image is not upload to the particular folder.

My Code:

 TextView messageText;
    Button uploadButton;
    int serverResponseCode = 0;
    ProgressDialog dialog = null;

    String upLoadServerUri = null;

    /**********  File Path *************/
    final String uploadFilePath = "/storage/sdcard0/";
    final String uploadFileName = "temp.jpg";

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        uploadButton = (Button)findViewById(R.id.uploadButton);
        messageText  = (TextView)findViewById(R.id.messageText);

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

        /************* Php script path ****************/
        upLoadServerUri = "http://example.com/android/uploadserver.php";

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

                dialog = ProgressDialog.show(MainActivity.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();        
                }
            });
    }

    public int uploadFile(String sourceFileUri) {


          String fileName = sourceFileUri;

          HttpURLConnection conn = null;
          DataOutputStream dos = null;  
          String lineEnd = "
";
          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.

 See uploaded file here : 

"
                                              +" http://www.androidexample.com/media/uploads/"
                                              +uploadFileName;

                                messageText.setText(msg);
                                Toast.makeText(MainActivity.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(MainActivity.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(MainActivity.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 
         } 
        }

And Php coding is:

       < ?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";
   }
   ? >
  • 写回答

2条回答 默认 最新

  • douqing5981 2014-08-28 08:33
    关注

    At last, i found my answer.

    package com.ipot.image_upload;
    
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.ProgressDialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.database.Cursor;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Environment;
    import android.provider.MediaStore;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.Toast;
    
    public class MainActivity extends Activity {
    
         ImageView viewImage;
            Button b,upp;
            String ppath;
            private ProgressDialog dialog = null;
            private int serverResponseCode = 0;
            private String upLoadServerUri = null;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
    
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            b=(Button)findViewById(R.id.btnSelectPhoto);
            upp=(Button)findViewById(R.id.up);
    
            upLoadServerUri="http://server.com/android/upload_image.php";
    
            viewImage=(ImageView)findViewById(R.id.viewImage);
            b.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    selectImage();
                }
            });
    
            upp.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    System.out.println("path value..."+ppath);
    
                    dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);
                    //messageText.setText("uploading started.....");
                     new Thread(new Runnable() {
                         public void run() {
                    int y=uploadFile(ppath);
                    }
    }).start();  
                }
            });
        }
    
      /*  @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds options to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }*/
    
          private void selectImage() {
    
            final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
    
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("Add Photo!");
            builder.setItems(options, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int item) {
                    if (options[item].equals("Take Photo"))
                    {
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                        startActivityForResult(intent, 1);
                    }
                    else if (options[item].equals("Choose from Gallery"))
                    {
    
                         System.out.println("before call ...");
                        Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent, 2);
    
                    }
                    else if (options[item].equals("Cancel")) {
                        dialog.dismiss();
                    }
                }
            });
            builder.show();
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (resultCode == RESULT_OK) {
                if (requestCode == 1) {
                    File f = new File(Environment.getExternalStorageDirectory().toString());
                    for (File temp : f.listFiles()) {
                        if (temp.getName().equals("temp.jpg")) {
                            f = temp;
                            break;
                        }
                    }
                    try {
                        Bitmap bitmap;
                        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    
                        bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
                                bitmapOptions); 
    
                        viewImage.setImageBitmap(bitmap);
    
    
                        String path = android.os.Environment
                                .getExternalStorageDirectory()
                                + File.separator+"temp.jpg";
                              //  + "Phoenix" + File.separator + "default";
    
                        System.out.println("image path..."+path);
    
                        ppath=path;
    
                        //uploadFile(ppath);
    
                      //  f.delete();
                        OutputStream outFile = null;
                        File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                        try {
                            outFile = new FileOutputStream(file);
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                            outFile.flush();
                            outFile.close();
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (requestCode == 2) {
    
                    Uri selectedImage = data.getData();
                    String[] filePath = { MediaStore.Images.Media.DATA };
                    Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePath[0]);
                    String picturePath = c.getString(columnIndex);
                    c.close();
                    Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
                    Log.w("path of image from gallery......******************.........", picturePath+"");
    
                    String selectedImagePath;
                    selectedImagePath = getPath(selectedImage);
    
                    System.out.println("before set image...");
                    viewImage.setImageBitmap(thumbnail);
                   // uploadFile(ppath);
                    System.out.println("image path from gallery..."+selectedImagePath);
    
                    ppath=selectedImagePath;
                }
            }
        }
    
        public int uploadFile(String ppath2) {
    
             String fileName = ppath2;
    
             HttpURLConnection conn = null;
             DataOutputStream dos = null;  
             String lineEnd = "
    ";
             String twoHyphens = "--";
             String boundary = "*****";
             int bytesRead, bytesAvailable, bufferSize;
             byte[] buffer;
             int maxBufferSize = 1 * 1024 * 1024; 
             File sourceFile = new File(ppath2); 
    
             if (!sourceFile.isFile()) {
    
                  dialog.dismiss(); 
    
                  Log.e("uploadFile", "Source File not exist :"+ppath);
    
                  runOnUiThread(new Runnable() {
                      public void run() {
                        //  messageText.setText("Source File not exist :"+ ppath);
                      }
                  }); 
    
                  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.
    
     See uploaded file here : 
    
    "
                                         +" F:/wamp/wamp/www/uploads";
                                   //messageText.setText(msg);
                                   Toast.makeText(MainActivity.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(MainActivity.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(MainActivity.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 
            }
    
    
        private String getPath(Uri uri) {
            // TODO Auto-generated method stub
    
            if( uri == null ) {
                // TODO perform some logging or show user feedback
                return null;
            }
            // try to retrieve the image from the media store first
            // this will only work for images selected from gallery
            String[] projection = { MediaStore.Images.Media.DATA };
            Cursor cursor = managedQuery(uri, projection, null, null, null);
            if( cursor != null ){
                int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            }
            // this is our fallback here
            return uri.getPath();
    
        }   
    }
    

    And my php code is,

    <?php
    $target_path1 = "uploads/";
    $randno=mt_rand(1,15000);
    /* Add the original filename to our target path.
    Result is "uploads/filename.extension" */
    $target_path1 = $target_path1 . basename($randno.$_FILES['uploaded_file']['name']);
    
    
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1)) {
        echo "The first file ".  basename($randno. $_FILES['uploaded_file']['name']).
        " has been uploaded.";
    } else{
        echo "There was an error uploading the file, please try again!";
        echo "filename: " .  basename( $_FILES['uploaded_file']['name']);
        echo "target_path: " .$target_path1;
    }
    ?>
    

    Thanks for all!!!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多