Android使用HTTP POST上传文件

6
我尝试了很多方法和答案,这些方法和答案都在Stack Overflow和其他博客中描述,目的是将Android应用程序中的文件上传到我的服务器,但是它们都没有对我起作用。
我使用了httpclient4.3.3.jar、httpcore4.3.3.jar和httpmime4.3.3.jar。
我没有收到任何错误消息,我的应用程序也可以正常工作。但是我的服务器上没有数据传输到来,我使用的是php服务器,以下是我的服务器端代码。
$file_path = "uploads/";

$file_path = $file_path.basename( $_FILES['file_data']['name']);
if(move_uploaded_file($_FILES['file_data']['tmp_name'], $file_path)) {
    echo "success";
} else{
    echo "fail";
}

请给我任何带有必需库的工作示例或代码。我已经花了很多天在这方面的工作上,请您提供一个完整的答案来帮助我。


你能发一下执行请求的那部分代码吗? - Rajesh
尝试这个方法https://dev59.com/FXI-5IYBdhLWcg3wF0Uc#5220954 - Vinothkumar Arputharaj
@ Rajesh,我已经发布了我的httprequest代码并使用了库。 - Vivek P Pillai
也许你没有评论。你正在创建一个HttpClient,但你还需要执行请求。我在代码中没有看到这部分。也许这就是它没有发送数据的原因。 - Rajesh
显示剩余2条评论
1个回答

6
请尝试这个。
 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 
     } 

您需要在您的项目中添加以下Jar文件,这里我给您提供直接下载链接。
  1. httpclient-4.2.2.jar
  2. httpmime-4.0.jar

我需要一个用于上传文件的HttpPost方法,你能给我提供一些可用的代码和适当的库吗? - Vivek P Pillai
3
这是一个上传文件到服务器的工作示例,您只需根据自己的代码修改这些代码即可。从这里下载库:httpclient-4.2.2.jarhttpmime-4.0.jar - Lavekush Agrawal
1
谢谢,它有效了。但我需要使用HttpPost方法上传文件。你有什么想法吗? - Vivek P Pillai
2
该示例是文件上传方法。 - AsepRoro

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接