Django ajax 文件上传
Posted
技术标签:
【中文标题】Django ajax 文件上传【英文标题】:Django ajax file upload 【发布时间】:2013-05-08 14:08:15 【问题描述】:所以我试图上传一个没有任何外部插件的文件,但我遇到了一些错误。
<form method="" action="" name='upload_form' id='upload_form' >
% csrf_token %
<input type='file' name='file' id='file' />
<input type='button' value='Upload' id='upload'/>
</form>
<script type='text/javascript'>
$(document).ready(function()
var csrf_token = $('input[name="csrfmiddlewaretoken"]').val();
$('#upload').click(function()
$.ajax(
csrfmiddlewaretoken: csrf_token,
type: 'POST',
url : 'upload',
enctype: "multipart/form-data",
data :
'file': $('#file').val()
,
success: function(data)
console.log(data)
)
)
)
</script>
我的服务器:
class ImageUploadView(LoginRequiredMixin, JSONResponseMixin, AjaxResponseMixin, CurrentUserIdMixin, View):
@method_decorator(csrf_protect)
def dispatch(self, *args, **kwargs):
return super(ImageUploadView, self).dispatch(*args, **kwargs)
def post_ajax(self, request, username):
print request.POST.get('file', None)
print request.FILES
# id = request.POST['id']
# path = 'pictures/'
# f = request.FILES['picture']
# destination = open(path, 'wb+')
# for chunk in f.chunks():
# destination.write(chunk)
# destination.close()
return HttpResponse("image uploaded")
我得到了一个<MultiValueDict: >
的请求。文件
我现在如何使用我的代码正确获取上传的文件?
【问题讨论】:
你不能用 Ajax 上传这样的文件。不幸的是,您确实需要一个插件,通过框架来完成,或者使用新的 html5 功能,如 FormData。 我如何异步处理 html5?有链接吗? blueimp.github.io/jQuery-File-Upload / script-tutorials.com/pure-html5-file-upload 【参考方案1】:这是我使用 javascript 上传文件的方法,希望对您有所帮助!只需将您的 $('#file') 作为参数传递。
function upload(field, upload_url)
if (field.files.length == 0)
return;
file = field.files[0];
var formdata = new FormData();
formdata.append('file_upload', file);
$.ajax(
url: upload_url,
type: 'POST',
data: formdata,
processData: false,
contentType: false,
success: console.log('success!')
);
[编辑]
这就是我在服务器端所做的(简化):
def save_file(dest_path, f, filename):
original_name, file_extension = os.path.splitext(f.name)
filename = filename + '-' + datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S') + file_extension
url = '/' + dest_path + '/' + filename
path = django_settings.MEDIA_ROOT + url
destination = open(path, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
return path
class FileUploadView(View):
def post(self, request, *args, **kwargs):
if request.FILES and request.FILES.get('file_upload'):
path = save_file(UPLOAD_TO,
request.FILES.get('file_upload'),
FILENAME)
return self.render_to_response()
【讨论】:
服务器端呢?【参考方案2】:我遵循本教程http://www.script-tutorials.com/pure-html5-file-upload/ 并在 php 部分中替换为:
class UploadImageView(LoginRequiredMixin, CurrentUserIdMixin, View):
@method_decorator(csrf_protect)
def dispatch(self, *args, **kwargs):
return super(UploadImageView, self).dispatch(*args, **kwargs)
def post(self, request, username):
path = 'myproject/media/pictures/guitar.jpg'
f = request.FILES['image_file']
destination = open(path, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
return HttpResponse("image uploaded")
也改变了这一行
<form id="upload_form" enctype="multipart/form-data" method="post" action=".">
% csrf_token %
【讨论】:
以上是关于Django ajax 文件上传的主要内容,如果未能解决你的问题,请参考以下文章