2013-08-05 73 views
0

我正在嘗試編寫一個Android應用程序,它接收用戶圖像並將其上載到服務器。我可以在手機上查看圖像,但從服務器複製文件時無法查看圖像。我正在使用Apache公共庫來做FTP上傳。該文件出現,大小正確,但無法打開。發送到服務器後JPEG損壞

public static void uploadImage(Bitmap bitmap,String path) 
    { 
     String filePath="RENT/images/capture/TESTFILE.jpg"; 
     try 
     { 
     FTPClient client = new FTPClient(); 
      client.connect("MY IP"); 
      client.login("USER", "PWD"); 
      client.enterLocalPassiveMode(); 
      Log.i("aaa","connected: "+client.isConnected()); 
      Log.i("aaa","going to addr: "+client.getRemoteAddress()); 
      FileInputStream fis = new FileInputStream(bitmapToFile(bitmap)); 
      Log.i("aaa","2-starting to upload file"); 
      client.storeFile(filePath, fis); 
      fis.close(); 
      client.logout(); 
      Log.i("aaa","3-file upload complete"); 
     } 
     catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    public static File bitmapToFile(Bitmap bitmap) throws IOException 
    { 
     File outputDir = con.getCacheDir(); 
     File outputFile = File.createTempFile("testFile", ".jpg", outputDir); 


     ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
     bitmap.compress(CompressFormat.JPEG, 90, bos); 
     byte[] bitmapdata = bos.toByteArray(); 

     //write the bytes in file 
     FileOutputStream fos = new FileOutputStream(outputFile); 
     fos.write(bitmapdata); 
     fos.flush(); 
     fos.close(); 

     return outputFile; 
    } 
} 
+0

請參考http://stackoverflow.com/a/8803503/1915697它 –

+0

可能重複的[如何將圖像上傳到服務器在Android?](http://stackoverflow.com/questions/8803430/how-to- android.writeBytes(「Content-Disposition:form-data; name =」uploaded_file「; filename =」「+ fileName +」「」+ upload-image-into-server-in-android) –

回答

0

我發現了一個解決方案。整個(工作)代碼如下:(需要apache庫)。

import org.apache.commons.net.ftp.FTP; 
import org.apache.commons.net.ftp.FTPClient; 
import org.apache.http.client.ClientProtocolException; 

我在這個項目中使用了4.0.1版本。

public static void uploadImage(String path) 
    { 
     FTPClient ftpClient = new FTPClient(); 
     try { 
      ftpClient.connect("IP"); 
      ftpClient.setFileType(FTP.BINARY_FILE_TYPE); 
      ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE); 
      ftpClient.setSoTimeout(10000); 
      ftpClient.enterLocalPassiveMode(); 
      if(ftpClient.login("USR", "PWD")) 
      { 
       Log.i("aaa","Path: "+path); 
       File sFile=new File(path); 
       if(!sFile.exists()) 
        Log.i("aaa","file not exist"); 
       FileInputStream fs= new FileInputStream(sFile); 
       String fileName = "xxx.jpg"; 
       Boolean result = ftpClient.storeFile("RENT/images/capture/" + fileName, fs); 
       Log.i("aaa","result: "+result); 
       if(result) 
        new File(path).delete(); 
      } 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

我需要將ftpClient.fileType和ftpClient.setFileTransferMode都設置爲二進制文件類型。

0

我不知道確切的問題...可能是它的圖像問題是PNG格式,你發送JPEG格式...如果不是這樣,那麼請檢查此方法...

公衆詮釋uploadFile(字符串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 

    } 

}

+0

這行代碼會拋出一個錯誤: lineEnd);你是否想要逃避其中一個引號?我如何向HTTPClient提供登錄憑證?謝謝! – Rilcon42