上传任何文件到服务器

问题描述:

我想写一个函数,将任何filev上传到我的服务器。我在互联网上搜索了所有内容,但没有使用任何外部库也没有用。有什么建议么?上传任何文件到服务器

+0

的可能的复制[我如何在Android中使用http发送文件从移动设备到服务器?(https://*.com/questions/4126625/如何做我发送一个文件在Android从移动设备到服务器使用http) –

试试这个

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

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