本文共 1375 字,大约阅读时间需要 4 分钟。
本篇主要讲的是ajax下的文件上传
模板html文件内容
编写文件上传js
function upload(){ // ajax上传文件 var file_input = $('#file_input'); if(file_input.val() == ''){ return false; } var formData = new FormData($('#fileupload_form')[0]); $.ajax({ type : 'POST', url : '/api/fileupload/', data : formData, dataType : 'json', contentType : false, processData : false, success : function(data){ if(data.info){ console.log('文件上传成功!'); return; } else { console.log('文件上传失败!'); return false; } }, error : function(){ console.log('文件上传失败!'); return false; } }); }
服务器端视图代码如下
class FileUpload(View): ''' 文件上传 ''' def post(self, request): try: file = request.FILES.get('file') if(file.size >= 2097152): # 当上传文件大于2M时抛出异常 raise RuntimeError('fileSizeError') except Exception as error: print(error)
POST提交过来的文件需要使用request.FILES.get()去获取,而不能直接使用request.POST.get()
非ajax文件上传
需要为form表单添加enctype属性,其值必须为multipart/form-data,请求方式依然为POST转载于:https://blog.51cto.com/14284354/2401345