javascript - request.FILES 返回 InMemoryUploadedFile
问题描述
我做了一个 api 来上传文件。为此,我使用了 Django 和 jQuery.ajax。我不知道如何阅读 File 这是我的 views.py 文件,它接收请求
def upload(request):
if request.method == 'POST':
print(request.FILES['image'].file)
data = request.FILES['image'].file.read()
print(type(data))
print(data)
# data.encode()
return JsonResponse(data={'message': 'recieved'})
这是我发送文件的 HTML 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<form id="form">
{% csrf_token %}
<input type="file" id="inp-fld">
<button type="submit">....</button>
</form>
</body>
<script type="text/javascript">
const csrftoken = getCookie('csrftoken');
jQuery.noConflict();
formdata = new FormData();
jQuery("#inp-fld").on("change", function() {
var file = this.files[0];
if (formdata) {
formdata.append("image", file);
console.log(formdata)
jQuery.ajax({
beforeSend: function(xhr){
xhr.setRequestHeader('X-CSRFToken', csrftoken)
},
url: "/upload",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success:function(data){
console.log(data)
}
});
}
});
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
</script>
</html>
这是 request.files 的输出
<MultiValueDict: {'file': [<InMemoryUploadedFile: WIN_20190920_22_49_37_Pro.jpg (image/jpeg)>]}>
这是 (type(request.FILES.get('file').read())) 的输出
<class 'bytes'>
我怎样才能得到我上传的图像
我目前对图像处理和字节的想法和经验为 0
我只想将收到的文件转换为 jpg/jpeg
解决方案
您可以将文件保存为:
f = request.FILES['file']
with open('some/file/name.txt', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
一件重要的事情是:
FILES
POST
仅当请求方法是并且<form>
发布到请求的方法是“时才包含数据enctype="multipart/form-data
。否则,FILES
将是一个空白的类似字典的对象。
<form id="form", enctype="multipart/form-data>
.....
</form>
可以点击以下链接了解更多详情。
推荐阅读
- vb.net - 阻止插入符号移动到组合框的前面
- oozie - 如何安排 Oozie 协调器 cron 在本地时区同时启动以考虑夏令时
- c# - 如何从随机字符串中提取子字符串?
- python - 使用 json_normalize 展平嵌套的 json
- graph - 在 Common Lisp 中表示有向无环图
- node.js - 使用 Node 8.11 时出现 ssh_exchange_identification 错误,但在使用 Node 4.7 时没有
- reactjs - 无法在本机基础中打开抽屉
- grpc - 如何使用nest.js创建不在控制器中的grpc客户端
- sql - 重复项的 SQL 结果 - Oracle
- python - VTK,Mayavi BUG:所有 `ButtonReleaseEvents` 都失败,但所有 `ButtonPressEvents` 工作?