在Android中上傳文件到服務(wù)器,通常需要以下步驟:
1、獲取文件路徑
2、創(chuàng)建HttpURLConnection對象
3、設(shè)置請求屬性
4、寫入數(shù)據(jù)
5、讀取響應(yīng)
6、關(guān)閉連接
以下是詳細的代碼示例:
import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; public class UploadToServer { // server url where the file will be posted private static final String UPLOAD_URL = "http://yourserverurl.com/upload"; public void uploadFile(String sourceFileUri) { String fileName = sourceFileUri; HttpURLConnection conn = null; DataOutputStream dos = null; String lineEnd = "r "; String twoHyphens = ""; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; File sourceFile = new File(sourceFileUri); if (!sourceFile.isFile()) { Log.e("Huzzaman", "Source File not exist :" + sourceFileUri); return; } try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(UPLOAD_URL); conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL 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", "KeepAlive"); conn.setRequestProperty("ENCTYPE", "multipart/formdata"); conn.setRequestProperty("ContentType", "multipart/formdata;boundary=" + boundary); conn.setRequestProperty("file", fileName); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("ContentDisposition: formdata; name="file";filename="" + fileName + """ + lineEnd); dos.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); // create a buffer of maximum size 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("Upload file to server", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 200) { // Toast message Runnable completeMsg = () > Toast.makeText(getActivity(), "File Upload Complete.", Toast.LENGTH_SHORT).show(); getActivity().runOnUiThread(completeMsg); } //close the streams // fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { ex.printStackTrace(); Log.e("Upload file to server", "error: " + ex.getMessage(), ex); } catch (Exception e) { e.printStackTrace(); Log.e("Upload file to server", "Could not upload file: " + e.getMessage(), e); } } }
在這個例子中,我們首先創(chuàng)建一個HttpURLConnection對象,然后設(shè)置請求屬性,包括請求方法、連接類型、內(nèi)容類型等,我們打開一個文件輸入流,讀取文件內(nèi)容并寫入HttpURLConnection的輸出流,我們讀取服務(wù)器的響應(yīng)并關(guān)閉連接。