发送到服务器后JPEG损坏

时间:2013-08-05 06:05:47

标签: android jpeg corruption

我正在尝试编写一个Android应用程序来获取用户图像并将其上传到服务器。我可以在手机上查看图像,但在从服务器复制文件时无法查看图像。我正在使用Apache commons库来进行FTP上传。显示文件,大小正确,但无法打开。

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

2 个答案:

答案 0 :(得分:0)

我不知道确切的问题...可能是你的图像是PNG格式而你发送的是JPEG格式的问题......如果不是这样的话请检查这种方法......

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 

     } 

}

答案 1 :(得分: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都设置为二进制文件类型。

相关问题