[英]no file on upload to django rest framework
更新:以下兩個答案均無效。 當我使用request.FILES [“ file”]時,出現鍵盤錯誤。
我正在使用django rest框架上載pdf文件,但請求進入並且沒有文件。 我正在嘗試從郵遞員上傳文件。 獲取請求有效。 任何幫助,非常感謝。
這是我的看法
@api_view(['PUT','GET'])
def upload_pdf(request):
if request.method == 'PUT':
myfile = request.POST.get('file')
print("myfile === {}".format(myfile))
if request.method == 'GET':
return Response({"message": "Hey there at least this works!"})
輸出:myfile ===無
在Django中,所有上傳的文件都將以request.FILES
結尾,而不是request.POST
。 這就是為什么您在發布數據中看不到該文件的原因。
問題不在於代碼,而在於郵遞員。 我不知道如何使用郵遞員,沒有人對郵遞員提出任何建議。 所以我只是用curl命令測試了它。
curl -XPOST -i -F file=@dir/to/test.pdf http://127.0.0.1:8000/api/upload_pdf
你可以試試這個
from rest_framework.parsers import FileUploadParser
class Fileupload(APIView):
parser_class = (FileUploadParser,)
def post(self, request, format=None):
file = request.FILES['file']
if 'file' not in request.data:
raise ParseError("Empty content")
model_obj = YourModel.objects.get_or_create()
model_obj.myfile.save(file.name, file, save=True)
希望能幫助到你
有關更多詳細信息,請參閱此
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.