前端代码:
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)})
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/281396.html