图像无法在Android服务器上传

时间:2015-08-27 11:18:15

标签: android android-imageview android-image android-photos

我从画廊获取图像并通过php放入服务器,一切都已完成但图像无法保存在服务器上请帮帮我

   public int uploadFile (String sourceFileUri) {


        String fileName = sourceFileUri;
       String upLoadServerUri="http://thinksl.com/taughtable/update.php";
        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); 
        int serverResponseCode = 0;
        StrictMode.ThreadPolicy th= new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(th);

        if (!sourceFile.isFile()) {



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

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

        }
             }); 

             return 0;

        }
        else
        {
             try { 

                   // open a URL connection to the Servlet
                 FileInputStream fileInputStream = new FileInputStream(sourceFile);
                 URL url = new URL(upLoadServerUri);
                //String uploaded_file="image";
                 // 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.e("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"
                                           ;

                              Toast.makeText(Edit_Profile.this, "File Upload Complete.", 
                                           Toast.LENGTH_SHORT).show();
                          }
                      });                
                 }    

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

            } catch (MalformedURLException ex) {


                ex.printStackTrace();

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

                        Toast.makeText(Edit_Profile.this, "MalformedURLException", 
                                                            Toast.LENGTH_SHORT).show();
                    }
                });

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

                e.printStackTrace();

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

         } 

       }

Php文件

   $target = "uploads/"; 
   $target1 =$target . date(U).( $_FILES['image']['name']);
   $path="http://thinksl.com/taughtable/uploads/";
   $image=$path . date(U).( $_FILES['image']['name']);
   move_uploaded_file($_FILES['image']['tmp_name'], $target1);

1 个答案:

答案 0 :(得分:1)

以下是我用于将图片上传到服务器的方法。

/**
 * Upload Image to server
 *
 * @param file              image to be saved
 * @param compressorQuality quality of image
 * @return path of uploaded image in server
 */
private String uploadImage(Bitmap file, int compressorQuality) {
    String final_upload_filename = "demo_image.png";
    String response = null;
    HttpURLConnection conn = null;
    try {
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "---------------------------14737809831466499882746641449";
        URL url = new URL("image_upload_url");
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        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", final_upload_filename);
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"userfile\"; filename=\"" + final_upload_filename + "\"" + lineEnd);
        dos.writeBytes("Content-Type: application/octet-stream" + lineEnd);
        dos.writeBytes(lineEnd);
        file.compress(CompressFormat.PNG, compressorQuality, dos);
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        dos.flush();
        dos.close();
        InputStream is = conn.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int bytesRead;
        byte[] bytes = new byte[1024];
        while ((bytesRead = is.read(bytes)) != -1) {
            baos.write(bytes, 0, bytesRead);
        }
        byte[] bytesReceived = baos.toByteArray();
        baos.close();
        is.close();
        response = new String(bytesReceived);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return response;
}

您可以使用以下方法:

Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
String server_response = uploadImage(bitmap, 100);

我希望它有所帮助!