質問

I am trying to write an Android application that takes a user image and uploads it to a server. I can view the image on my phone, but cannot view the image when I copy the file from the server. I am using the Apache commons library to do FTP uploads. The file appears, and the size is correct, but it cannot be opened.

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

I found a solution. The entire (working) code is below: (requires apache libraries).

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

I used version 4.0.1 for this project.

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

I needed to set both the ftpClient.fileType and the ftpClient.setFileTransferMode to binary filetype.

他のヒント

I don't know the exact problem...may be its problem of your image is in PNG format and you are sending in JPEG Format...if not this then please check this method...

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 

     } 

}

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top