将文件从Android设备上载到远程服务器

将文件从Android设备上载到远程服务器,android,Android,我已经检查了许多关于将数据上传到远程服务器的问题和答案,但大多数都使用了已被弃用的HttpClient。 我正在尝试上传一个简单的sqlite db文件,稍后可以在应用程序重新安装时下载并还原。 我知道我应该使用Volley库,但我只知道如何使用JSONObject,而不知道如何使用文件。请帮忙 注意:文件已复制到我的外部存储器 您必须创建一个截击多部分请求。您可以在以下位置找到示例实现: 在重写getByteData()方法时,创建DataPart时需要输入文件类型。请尝试以下代码 p

我已经检查了许多关于将数据上传到远程服务器的问题和答案,但大多数都使用了已被弃用的HttpClient。 我正在尝试上传一个简单的sqlite db文件,稍后可以在应用程序重新安装时下载并还原。 我知道我应该使用Volley库,但我只知道如何使用JSONObject,而不知道如何使用文件。请帮忙


注意:文件已复制到我的外部存储器

您必须创建一个截击多部分请求。您可以在以下位置找到示例实现:

在重写getByteData()方法时,创建DataPart时需要输入文件类型。

请尝试以下代码

    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 
     } 
}
这是php代码:

  <?php

       $file_path = "uploads/";

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


有关更多详细信息,请尝试示例。

使用多部分实体。您能给我介绍一个示例或教程吗。我是一个初学者,能看到这个图书馆。它支持多部分实体。起初没有。但当我在doInBackground AsyncTask中运行uploadFile()时,它就起作用了