django 上传文件

在handle_uploaded_file()函数自己修改存储位置就可以使用了
注:从客户端发送请求时文件放到<input name=img > 。 要和后台的request.FILES['img']一致。

Step1 #配置urls.py

from .views import upload_img

urlpatterns = [
    path('img/', upload_img, name = 'img_service')
]

step2 # view.py

from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
import time


def handle_uploaded_file(file, file_name):
    with open("D:\\images\\" + file_name, "wb+") as destination:
        for chunk in file.chunks():
            destination.write(chunk)


@csrf_exempt
def upload_img(request):
    if request.method == 'POST':
        exist = request.FILES.__contains__("img")
        file = None
        if exist:
            file = request.FILES['img']
        if file is not None and file.name is not None:
            #当前的时间戳+文件名称 生成新的文件名
            file_name = str(time.time()).split(".")[0] + file.name
            #调用文件写入到磁盘的函数
            handle_uploaded_file(file, file_name)
            return JsonResponse({"msg": "ok"})
        else:
            JsonResponse.status_code = 400
            return JsonResponse({"msg": "文件为空"})
    return HttpResponse(status = 403)

猜你喜欢

转载自blog.csdn.net/weixin_38570967/article/details/81261852