在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python/ Python的Django-rest-framework框架獲取Http上傳文件

Python的Django-rest-framework框架獲取Http上傳文件保存后文件內容不對

獲取上傳文件后,將上傳文件流寫入到服務器文件中后.文件內容多了http流相關信息

--X-INSOMNIA-BOUNDARY
Content-Disposition: form-data; name="file"; filename="a.txt"
Content-Type: text/plain



Hello




--X-INSOMNIA-BOUNDARY--

應該怎么獲取上傳文件信息保存的時候,只會是原文件.


補充下我的源代碼:


class UploadView(APIView):
    '''
    上傳文件專用
    '''

    parser_classes = (FileUploadParser, )

    def put(self, request, filename, format = None):
        '''
        上傳
        '''

        up_file = request.data['file']
        base_dir = settings.BASE_DIR

        print filename


        storage = base_dir + '/' + 'storage/'
        new_file = storage + up_file.name

        with open(new_file, 'wb+') as destination:
            for chunk in up_file.chunks():
                destination.write(chunk)

            destination.close()

        # up_file.new_file('file', new_file, up_file.content_type, up_file.size, up_file.charset, up_file.content_type_extra)


        # with open(new_file, 'wb+') as destination:
        #     for line in up_file:
        #         destination.write(line)
        #     destination.close()
        #     # destination.write(up_file.multiple_chunks())
        #     # destination.close()

        return Response(up_file.name, status.HTTP_201_CREATED)
回答
編輯回答
鹿惑

看你的保存內容應該是使用類似BaseHTTPServer這種python自帶的類完成的上傳服務器。
https://github.com/smilejay/p...
如果是這樣的話,那些http流的相關信息是沒有什么好的辦法的,只能自己通過類似readline的方式,一行一行的讀取,并且手動去除http相關信息。
所幸這些都是http信息都是有相關標準的,例如 1-4 行為http信息, 5-(-2)行為上傳信息,最后一行為http信息(這只是隨便舉得一個例子)
所以想要通過這種方式來完成上傳文件的話,需要自己去研究下rfc標準:
http://www.ietf.org/rfc/rfc1867
http://www.vivtek.com/rfc1867...

但是看你標簽上是有django的,所以應該會更簡單省事些的方式,就是使用djangorequest.FILES了。
參考地址:
https://docs.djangoproject.co...
示例:

# 獲取文件名
request.FILES['filename'].name
# 獲取全部文件
for filename, file in request.FILES.iteritems():
    name = request.FILES[filename].name
    # 文件內容(這個不確定,請自行查看文檔)
    file.readall()
2018年3月13日 13:43