将文件从 android 上传到服务器失败

Uploading file from android to server fails

我正在尝试将文件上传到服务器。我尝试通过两种方式做到这一点。

第一种方法

这是第一种方法的代码:

String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(fileName);

try {
    // open a URL connection to the Servlet
    FileInputStream fileInputStream = new FileInputStream(sourceFile);
    URL url = new URL("http://localhost:8000/cgi-bin/test.py?action=upload&code=123");

    // 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("file", fileName);

    dos = new DataOutputStream(conn.getOutputStream());

    dos.writeBytes(twoHyphens + boundary + lineEnd);
    dos.writeBytes("Content-Disposition: form-data; name=\"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)
    int serverResponseCode = conn.getResponseCode();
    String serverResponseMessage = conn.getResponseMessage();

    Log.i("uploadFile", "HTTP Response is : "
            + serverResponseMessage + ": " + serverResponseCode);

    if(serverResponseCode == 200){
    }

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

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

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

int serverResponseCode = conn.getResponseCode();行代码抛出如下异常:

java.io.EOFException
            at libcore.io.Streams.readAsciiLine(Streams.java:203)
            at libcore.net.http.HttpEngine.readHeaders(HttpEngine.java:609)
            at libcore.net.http.HttpEngine.readResponseHeaders(HttpEngine.java:562)
            at libcore.net.http.HttpEngine.readResponse(HttpEngine.java:814)
            at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:293)
            at libcore.net.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:505)
            at ir.fajrdev.uploader.HTTP.HTTPUploader.upload1(HTTPUploader.java:241)
            at ir.fajrdev.uploader.HTTP.HTTPUploader.uploadAllFiles(HTTPUploader.java:48)
            at ir.fajrdev.uploader.fragments.UploadFragment.run(UploadFragment.java:74)
            at java.lang.Thread.run(Thread.java:856)

我已经搜索过这个异常,它似乎是一个错误,但没有一个答案对我有用。

第二种方法

所以我尝试了另一种方法,如下所示:

File file = new File(f.address);

HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("http://localhost:8000/cgi-bin/test.py?action=upload&code=123");

try {
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    FileBody fb = new FileBody(file);
    entityBuilder.addPart("file", fb);

    HttpEntity entity = entityBuilder.build();

    httpPost.setEntity(entity);

    HttpResponse response = httpClient.execute(httpPost, localContext);
    String result = EntityUtils.toString(response.getEntity());
    if ("done".equals(result)) {
        DatabaseManager.sharedDB().fileUploaded(f.id);
    }
} catch (IOException e) {
    e.printStackTrace();
}

这里的问题是响应应该是 done 但它是一个空字符串。从服务器端登录后,它说没有属性 filename。服务器正在运行,因为我可以使用我之前编写的 iOS 应用程序上传文件,但我也不能在 android 应用程序上完成此操作。

我检查了两种方法中发送的数据,它们看起来很相似,除了第二种方法中有一行 Content-Type: application/octet-stream 在第一种方法输出中不存在。

抱歉问了这么长的问题:)

使用这个示例代码,它会工作正常

http://androidexample.com/download_android_example/download.html?view=download&token=fe9fc289c3ff0af142b6d3bead98a923

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

有一个愚蠢的问题:)

我的应用程序运行 NanoHttpd 服务器,我将文件上传到它。然后我有一个按钮可以将文件上传到网上的服务器。问题是我上传任何上传给我的东西! (我没有把参数放在问题的代码中,这样会更容易找到解决方案)。 NanoHttpd 会为每个已上传的文件创建一个名为 file 的参数。因此,当我将所有这些参数上传到服务器时,它会看到 file 参数但没有文件名。所以我刚刚删除了 file 参数,现在第二种方法效果很好!

P.S: 还是第一种方法不行(题中的代码和答案中的代码都不行)。现在不知道为什么?!