1. Django系列之Django与ajax上传文件
html代码如下:
<div class="form-group">
<label for="exampleInputFile">附件上传</label>
<input type="file" name="file" id="file_upload">
<button type="button" class="btn btn-default" onclick="FileUpload()">开始上传附件</button>
</div>
jqeury代码如下:
// 上传附件到方法
function FileUpload() {
var form_data = new FormData();
var file_info = $('#file_upload')[0].files[0];
form_data.append('file',file_info);
//if(file_info==undefined)暂且不许要判断是否有附件
//alert('你没有选择任何文件');
//return false
//}
// 提交ajax的请求
$.ajax({
url:"{% url 'post_apply_data' %}",
type:'POST',
data: form_data,
processData: false, // tell jquery not to process the data
contentType: false, // tell jquery not to set contentType
success: function(callback) {
console.log(order_id)
}
}); // end ajax
}
django-view代码如下:
def handle_upload(request):
file_obj = request.FILES.get('file')
if file_obj: # 处理附件上传到方法
request_set = {}
print('file--obj', file_obj)
#user_home_dir = "upload/%s" % (request.user.userprofile.id)
accessory_dir = settings.accessory_dir
if not os.path.isdir(accessory_dir):
os.mkdir(accessory_dir)
upload_file = "%s/%s" % (accessory_dir, file_obj.name)
recv_size = 0
with open(upload_file, 'wb') as new_file:
for chunk in file_obj.chunks():
new_file.write(chunk)
order_id = time.strftime("%Y%m%d%H%M%S",time.localtime())
cache.set(order_id,upload_file)
return HttpResponse(order_id)
至此,我们可以通过ajax正常上传文件了。