iT邦幫忙

0

要如何使用前端js上傳至python django?[以解決]

  • 分享至 

  • xImage

結果是不能加 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測試後沒問題
如圖:
postman圖片

請問各位大大有發現我是哪裡有打錯或是理解錯嗎? 感謝各位

增廣建文 iT邦研究生 5 級 ‧ 2023-10-29 00:18:32 檢舉
Postman有帶Authorization?
ho0527 iT邦新手 5 級 ‧ 2023-10-29 09:43:04 檢舉
應該是沒有
ho0527 iT邦新手 5 級 ‧ 2023-10-29 09:49:23 檢舉
我註解掉
ajax.setRequestHeader("Authorization","Bearer "+localStorage.getItem("token"))
一樣是不能上傳
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答