結果是不能加 ajax.setRequestHeader("Content-type","multipart/form-data;boundary="+Date.now())😑
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<input type="file" class="file" name="file" id="file">
<script src="index.js"></script>
</body>
</html>
// 前端index.js
document.getElementById("file").onchange=function(){
let ajax=new XMLHttpRequest()
let formdata=new FormData()
formdata.append("file",this.files[0])
ajax.onload=function(){
let data=JSON.parse(this.responseText)
if(data["success"]){
alert("結果: "+data["data"])
}else{
alert(data["data"])
}
}
ajax.open("POST","/backend/test/upload/"+questionid,true)
ajax.setRequestHeader("Content-type","multipart/form-data;boundary="+Date.now())
ajax.setRequestHeader("Authorization","Bearer "+localStorage.getItem("token"))
ajax.send(formdata)
}
# 後端/backend/test/upload/
# import
import bcrypt
import hashlib
import json
import os
import random
import re
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
from django.utils.text import get_valid_filename
from django.views.decorators.http import require_http_methods
from rest_framework import status
from rest_framework.decorators import api_view,renderer_classes
from rest_framework.renderers import JSONRenderer
from rest_framework.response import Response
def uploadfile(path,file):
try:
with open(os.path.join(path,file.name),"wb") as f:
for chunk in file.chunks():
f.write(chunk)
except Exception as error:
printcolorhaveline("fail","[ERROR] function uploadfile error: "+str(error),"")
@api_view(["POST"])
def newans(request,questionid):
try:
print(request.POST)
print(request.FILES)
uploadfile("./test/upload",request.FILES["file"])
return Response({
"success": True,
"data": ""
},status.HTTP_200_OK)
except Exception as error:
printcolorhaveline("fail","[ERROR] "+str(error),"")
return Response({
"success": False,
"data": "[ERROR] unknow error pls tell the admin error:\n"+str(error)
},status.HTTP_500_INTERNAL_SERVER_ERROR)
而他會輸出
<QueryDict: {}>
<MultiValueDict: {}>
[ERROR] 'file'
[27/Oct/2023 19:30:47] "POST /test/upload/1 HTTP/1.0" 500 81
使用postman測試後沒問題
如圖:
請問各位大大有發現我是哪裡有打錯或是理解錯嗎? 感謝各位