一、前言
在移動設備中,文件上傳是一個非常普遍的需求。本文將探討如何使用Python編寫後端代碼,實現在Android應用中進行文件上傳。
二、實現步驟
1.獲取文件流
在Android應用中,首先需要通過代碼獲取文件的字節流。可以通過如下代碼實現:
File file = new File(filePath); FileInputStream fileInputStream = new FileInputStream(file);
其中,filePath為文件的路徑。
2.發送HTTP請求
獲取文件流後,需要將文件流發送給後端。可以使用HTTP協議進行通信。可使用Python中的requests庫來發送HTTP請求。如下所示:
import requests def upload_file(file): url = "http://example.com/upload" # 文件上傳的URL files = {'file': file} # 將文件流封裝到字典中 response = requests.post(url, files=files) # 發送POST請求 return response.text
其中,file為文件的字節流。
3.接收文件
在後端,需要接收前端發來的文件流,並將其保存到服務器上。使用Python中的Flask框架可以輕鬆地實現該功能。
from flask import Flask, request app = Flask(__name__) @app.route('/upload', methods=['POST']) def upload(): file = request.files['file'] # 獲取文件流 file.save('./upload_file') # 將文件保存到服務器指定路徑 return 'file upload success' if __name__ == '__main__': app.run()
其中,’./upload_file’為服務器上文件保存的路徑。
三、代碼示例
下面是完整示例代碼:
Android代碼:
File file = new File(filePath); FileInputStream fileInputStream = new FileInputStream(file); new Thread(new Runnable() { @Override public void run() { String result = uploadFile(fileInputStream); Log.d(TAG, "file upload result: " + result); } }).start(); public String uploadFile(FileInputStream fileInputStream) { String result = ""; String url = "http://example.com/upload"; try { URL requestUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) requestUrl.openConnection(); conn.setConnectTimeout(10000); conn.setReadTimeout(15000); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY); String uuid = UUID.randomUUID().toString(); String end = "\r\n"; String twoHyphens = "--"; DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); // 發送文件信息 dos.writeBytes(twoHyphens + BOUNDARY + end); dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + uuid + "\"" + end); dos.writeBytes(end); // 發送文件流 byte[] buffer = new byte[1024]; int len = -1; while ((len = fileInputStream.read(buffer)) != -1) { dos.write(buffer, 0, len); } dos.writeBytes(end); dos.writeBytes(twoHyphens + BOUNDARY + twoHyphens + end); dos.flush(); // 獲取響應結果 InputStreamReader reader = new InputStreamReader(conn.getInputStream()); BufferedReader bufferedReader = new BufferedReader(reader); String line; while ((line = bufferedReader.readLine()) != null) { result += line; } reader.close(); dos.close(); } catch (Exception e) { e.printStackTrace(); } return result; }
Python代碼:
from flask import Flask, request import uuid app = Flask(__name__) @app.route('/upload', methods=['POST']) def upload(): file = request.files['file'] # 獲取文件流 filename = str(uuid.uuid1()) # 使用uuid生成文件名 file.save('./upload_files/'+filename) # 將文件保存到服務器指定路徑 return 'file upload success' if __name__ == '__main__': app.run()
四、總結
本文介紹了實現在Android應用中進行文件上傳的具體步驟,包括獲取文件流、發送HTTP請求和接收文件等。同時,提供了完整的Android和Python代碼示例。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/278910.html