本文共 2982 字,大约阅读时间需要 9 分钟。
在开始解决这个问题之前,首先要理解Django如何处理文件上传请求。这涉及到客户端和服务器端的协调工作,包括请求的发送、文件的接收和存储。
如果需要将文件上传到服务器,主要步骤是:
enctype="multipart/form-data"
,这会告诉服务器这是一个文件上传请求。:requests.post()
方法将文件内容发送到指定的URL。这里是一个示例:
import requestsimport osBASE_DIR = os.path.dirname(os.path.abspath(__file__))if __name__ == "__main__": url = "http://127.0.0.1:8001/gen_model/predict/" while True: input_content = input('输入图片路径(按回车退出):').strip() if not input_content: input_content = 'test.png' if input_content == 'q': break file_path = os.path.join(BASE_DIR, 'media', input_content) if not os.path.exists(file_path): print('图片文件不存在!请检查路径是否正确。') continue file_name = os.path.basename(file_path) file_data = open(file_path, 'rb') # 提取文件扩展名 ext = os.path.splitext(file_path)[1] headers = {'_enetcode': 'multipart/form-data'} files = {'img': (file_name, file_data, 'image/' + ext)} response = requests.post(url, headers=headers, files=files) print(f"上传状态:{response.status_code}") print(f"预测结果:{response.text}")
接下来配置Django服务器端接收文件的逻辑:
APIView
来处理HTTP请求。post
方法中,获取文件,并将其存储到媒体文件夹。from django.views.decorators.csrf import csrf_exemptfrom django.views.generic.base import Viewfrom django.conf import settingsfrom django.shortcuts import redirectclass PredictView(View): @csrf_exempt def post(self, request): file = request.FILES.get('img', None) if not file: return redirect('/') file_path = os.path.join(settings.MEDIA_ROOT, '上传的图片') file_name = os.path.basename(file.name) file_ext = os.path.splitext(file.name)[1] file_path = os.path.join(file_path, file_name) # 创建目标路径 if not os.path.exists(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) # 保存文件 with open(file_path, 'wb') as fp: for chunk in file.chunks(): fp.write(chunk) return redirect(f'/image/{file_path.split(os.path.sep)[-1:]}')
在页面中添加文件上传的表单,确保使用正确的enctype
:
图片上传 图片上传工具
确保Django的媒体文件配置:
在 settings.py 中:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')MEDIA_URL = '/media/'
在 URLs.py 中,确保有:
from django.urls import include, pathurlpatterns = [path('gen_model/predict/', include('predict.urls')),]
3. **创建 include 模块(如果没有):**```pythonfrom django.urls import re_pathfrom . import PredictViewurlpatterns = [ re_path(r'^gen_model/predict/', PredictView.as_view()),]
通过以上步骤,Django文件上传应该能正常运行。你可以测试上传一个图片,看看是否能成功保存到服务器,并接收到预期的响应。
转载地址:http://nictz.baihongyu.com/