- 使用简单的表单上传文件到django框架 form表单需要指定 enctype="multipart/form-data" 前端代码:
<!DOCTYPE html>
<html>
<head>
<title>uploadFile</title>
</head>
<body>
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="myFile">
<input type="submit" value="提交" />
</form>
</body>
</html>
后端代码:
def upload(request):
##request.FILES 为类字典类型,健为前段name指定的值,字典值为UploadFile对象,前端form中需要指定enctype="multipart/form-data"
##<input type="file" name="myFile">
uploadFileObj = request.FILES['myFile']
uploadFileName = uploadFileObj.name
uploadFileSize = uploadFileObj.size
##上传文件
with open(uploadFileName,"wb") as saveFile:
for chunk in uploadFileObj.chunks():
saveFile.write(chunk)
return HttpResponse('file upload OK')
- 使用ajax上传文件,不刷新当前页面,后端代码不变 html页面:
{% load static%}
<!DOCTYPE html>
<html>
<head>
<title>uploadFile</title>
<script src="{% static 'jquery-3.3.1.min.js' %}"></script>
<script>
function upload(){
var formData = new FormData();
var fileObj = $("#myFile")[0].files[0];
console.log(fileObj);
formData.append("myFile",fileObj);
console.log(formData);
$.ajax({
url:"upload",
type:"post",
data:formData,
contentType:false, // 一定要有
processData:false, // 一定要有,否则可能js报错: Uncaught TypeError: Illegal invocation
success: function(response){
$('#info').text(response);
},
});
}
</script>
</head>
<body>
<input type="file" name='myFile' id='myFile'>
<button type="button" onclick="upload()">upload</button>
<div id="info"></div>
</body>
</html>