2017-06-15 116 views
0

我想寫一個函數,將任何filev上傳到我的服務器。我在互聯網上搜索了所有內容,但沒有使用任何外部庫也沒有用。有什麼建議麼?上傳任何文件到服務器

+0

的可能的複製[我如何在Android中使用http發送文件從移動設備到服務器?(https://stackoverflow.com/questions/4126625/如何做我發送一個文件在Android從移動設備到服務器使用http) –

回答

3

試試這個

public int uploadFile(String sourceFileUri, String destUri) 
{ 
    String fileName = sourceFileUri; 
    Log.e("YOUR_TAG", "uploading file: " + sourceFileUri); 

    HttpURLConnection conn; 
    DataOutputStream dos; 
    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() && !sourceFile.exists()) 
    { 
     Log.e(YOUR_TAG, "Source File not exist :" + imagepath); 
     return 0; 

    } else { 

     try 
     { 
      // open a URL connection to the Servlet 
      FileInputStream fileInputStream = new FileInputStream(sourceFile); 
      URL url = new URL(destUri); 
      // 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); 
      bytesAvailable = fileInputStream.available(); 
      bufferSize = Math.min(bytesAvailable, maxBufferSize); 
      buffer = new byte[bufferSize]; 
      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); 
      } 

      dos.writeBytes(lineEnd); 
      dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 
      serverResponseCode = conn.getResponseCode(); 
      String serverResponseMessage = conn.getResponseMessage(); 
      Log.i(YOUR_TAG, "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); 

      if (serverResponseCode == 200) 
      { 
       Log.d(YOUR_TAG, "success: " + sourceFileUri); 
       //do your stuff here 
      } 
      fileInputStream.close(); 
      dos.flush(); 
      dos.close(); 

     } catch (MalformedURLException ex) { 

      ex.printStackTrace(); 
      Log.e(YOUR_TAG, "error: " + ex.getMessage(), ex); 

     } catch (Exception e) { 

      e.printStackTrace(); 
      Log.e(YOUR_TAG, "Exception : " + e.getMessage(), e); 

     } 
     return serverResponseCode; 
    } 
} 
+0

謝謝你,這工作! – win

0
try { 
      String uploadId = UUID.randomUUID().toString(); 

      //Creating a multi part request 
      new MultipartUploadRequest(this, uploadId, UPLOAD_URL) 
        .addFileToUpload(path, "f_url") //Adding file 
        .addHeader("Authorization", "Bearer " + token) //Adding token 
        .setNotificationConfig(new UploadNotificationConfig()) 
        .setMaxRetries(2) 
        .startUpload(); //Starting the upload 

     } catch (Exception exc) { 
      Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show(); 
     }