您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)Android中如何使用HttpURLConnection實(shí)現(xiàn)一個(gè)文件上傳,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
客戶端代碼:
public static String uploadFile(String uploadUrl, String filePath) { Log.v(TAG, "url:" + uploadUrl); Log.v(TAG, "filePath:" + filePath); String nextLine = "\r\n"; String dividerStart = "--"; String boundary = "******"; try { URL url = new URL(uploadUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setChunkedStreamingMode(1024 * 256); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); // 設(shè)置Http請(qǐng)求頭 connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Charset", "UTF-8"); //必須在Content-Type 請(qǐng)求頭中指定分界符 connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); //定義數(shù)據(jù)寫入流,準(zhǔn)備上傳文件 DataOutputStream dos = new DataOutputStream(connection.getOutputStream()); dos.writeBytes(dividerStart + boundary + nextLine); //設(shè)置與上傳文件相關(guān)的信息 dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + filePath.substring(filePath.lastIndexOf("/") + 1) + "\"" + nextLine); dos.writeBytes(nextLine); FileInputStream fis = new FileInputStream(filePath); byte[] buffer = new byte[1024 * 32]; int count; // 讀取文件內(nèi)容,并寫入OutputStream對(duì)象 while ((count = fis.read(buffer)) != -1) { dos.write(buffer, 0, count); } fis.close(); dos.writeBytes(nextLine); dos.writeBytes(dividerStart + boundary + dividerStart + nextLine); dos.flush(); // 開始讀取從服務(wù)器傳過來(lái)的信息 InputStream is = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); String result = br.readLine(); dos.close(); is.close(); connection.disconnect(); return result; } catch (IOException e) { e.printStackTrace(); } return null; }
服務(wù)器端代碼:
看完上述內(nèi)容,你們對(duì)Android中如何使用HttpURLConnection實(shí)現(xiàn)一個(gè)文件上傳有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。