编程语言
首页 > 编程语言> > python文件上传

python文件上传

作者:互联网

前端代码:

  html

<input id="fileUpload" type="file" name="upload">
<input type="button" @click="submitfile" value="Upload">

  js

submitfile() {
            var formData = new FormData()
            var formData = new window.FormData()
            formData.append("f1",$("#fileUpload")[0].files[0]);
            console.log(formData)
            //开始Ajax请求
            var options = {  // 设置axios的参数
                url: this.baseUrl+'/upload_action/',
                data: formData,
                method: 'post',
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            }
            axios(options).then((res) => {
                console.log(res)
            })
        },

  

后端:

def upload_action(request):
    try:
        # 1.获取上传的文件
        pic = request.FILES['f1']
        print(pic)
        # 2.创建文件
        save_path = '%s/%s' % (MEDIA_ROOT, pic.name)
        with open(save_path, 'wb') as f:
            # 获取上传文件的内容并写到创建文件中
            # pic.chunks():分块的返回文件
            for content in pic.chunks():
                f.write(content)
        return JsonResponse({'code': 1, 'data': pic.name})
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': "Upload failed:" + str(e)})

  

标签:文件,python,data,formData,pic,var,上传
来源: https://www.cnblogs.com/mango1997/p/16609636.html