实现了单文件上传,不会多文件上传,目前前端用一个 form 表单,进行多文件选择,但不太清楚,前端怎么获取选择的多 文件,并且改送给后端,请教一下各位,应该怎么实现多文件上传?
前端:
<div class="input-group">
<form action="/manage/upload/" method="post" enctype="application/x-www-form-urlencoded" ><input id="file_upload" name="fileupload" accept="image/png, image/jpeg" multiple="multiple" type="file" value="" /><input id="file_upload" type="button" value="上传" onclick="FileUpload()"/>
</form>
</div>
//上传图像
function FileUpload() {
$("#prompt").hide();
if ($("#file_upload").val() === ""){
$("#imgprompt").show();
return false;
}
$("#imgprompt").hide();
$("#loading").show();
var form_data = new FormData();
var file_info =$('#file_upload')[0].files[0];
form_data.append('file',file_info);
console.log(form_data);
$.ajax({
url:'/manage/upload/',
type:'POST',
data: form_data,
processData: false,
contentType: false,
success: function(callback) {
console.log('ok');
$("#loading").hide();
$("#prompt").show();
}
});
}
后端:
def upload(request):
if request.method == 'POST':
file_obj = request.FILES.get('file')
print("file_obj.name", file_obj, file_obj.name)
f = open(os.path.join('upload', file_obj.name), 'wb')
for chunk in file_obj.chunks():
f.write(chunk)
f.close()
return HttpResponse('OK')
1
Outliver0 2018-12-14 10:54:38 +08:00
request.FILES.getlist
|
2
careofzm 2018-12-14 11:17:47 +08:00
我是用 restframework, 大致上是这样实现的, 这不是上传图片, 希望对你有帮助
from rest_framework.parsers import FormParser, MultiPartParser from rest_framework.response import Response class MultipleFileSerializer(serializers.Serializer): files = serializers.ListField(child=serializers.FileField()) class UserViewset(ModelViewSet): serializer_class = UserSerializer pagination_class = UserPagination parser_classes = (FormParser, MultiPartParser) def create(self, request, *args, **kwargs): print(dir(request)) print(request.FILES) text = request.FILES['file1'].read() + request.FILES['file2'].read() return Response(text) |
3
yim7 2018-12-17 09:59:27 +08:00
这有什么问题,多个文件就有多个 form 字段
|