aiohttp request.multipart()从浏览器上传文件

时间:2018-05-25 12:56:15

标签: python vue.js multipartform-data aiohttp

浏览器使用vue element-ui el-upload组件上传文件,aiohttp作为后端接收表单数据然后保存。但是aiohttp request.multipart()总是空白但是request.post()就可以了。

vue:

   <el-upload class="image-uploader" 
        :data="dataObj" 
         drag 
         name="aaa"
        :multiple="false" 
        :show-file-list="false"
        :action="action"  -> upload url,passed from outer component
        :on-success="handleImageScucess">
      <i class="el-icon-upload"></i>
    </el-upload>

export default {
  name: 'singleImageUpload3',
  props: {
    value: String,
    action: String
  },
  methods: {
   handleImageScucess(file) {
      this.emitInput(file.files.file)
    },

  }

aiohttp:不工作

 async def post_image(self, request):

        reader = await request.multipart()

        image = await reader.next()
        print (image.text())
        filename = image.filename
        print (filename)
        size = 0
        with open(os.path.join('', 'aaa.jpg'), 'wb') as f:
            while True:
                chunk = await image.read_chunk()

                print ("chunk", chunk)
                if not chunk:
                    break
                size += len(chunk)
                f.write(chunk)
        return await self.reply_ok([])

aiohttp:work

async def post_image(self, request):
        data = await request.post()
        print (data)
        mp3 = data['aaa']

        filename = mp3.filename

        mp3_file = data['aaa'].file

        content = mp3_file.read()
        with open('aaa.jpg', 'wb') as f:
            f.write(content)
        return await self.reply_ok([])

浏览器控制台:

enter image description here

我错过了什么错误?请帮我解决,提前谢谢。

1 个答案:

答案 0 :(得分:0)

我想您可能已经在aiohttp document about file upload server上查看了示例。但是,该代码段含糊不清,并且该文档无法很好地说明自身。

经过一段时间的研究,我发现request.multipart()实际上产生了一个MultipartReader实例,该实例每次调用{{1}时都会处理multipart/form-data请求一个字段},产生另一个.next()实例。

在您不工作的代码中,BodyPartReader所在的行实际上从表单数据中读取了整个字段,您无法确定它实际上是哪个字段。可能是image = await reader.next()字段,token字段,key字段,filename字段...或其中任何一个。因此,在您无法正常工作的示例中,aaa协程函数将仅处理请求数据中的一个字段,并且您不能十分确定它是post_image文件字段。

这是我的代码段,

aaa

上面的代码段也可以在单个请求中处理多个文件,这些文件具有重复的字段名,在您的示例中为'aaa'。 async def post_image(self, request): # Iterate through each field of MultipartReader async for field in (await request.multipart()): if field.name == 'token': # Do something about token token = (await field.read()).decode() pass if field.name == 'key': # Do something about key pass if field.name == 'filename': # Do something about filename pass if field.name == 'aaa': # Process any files you uploaded filename = field.filename # In your example, filename should be "2C80...jpg" # Deal with actual file data size = 0 with open(os.path.join('', filename), 'wb') as fd: while True: chunk = await field.read_chunk() if not chunk: break size += len(chunk) fd.write(chunk) # Reply ok, all fields processed successfully return await self.reply_ok([]) 标头中的filename应该由浏览器本身自动填写,因此不必担心Content-Disposition

顺便说一句,当处理请求中的文件上载时,filename将消耗大量内存来加载文件数据。因此,在涉及文件上传时,应避免使用data = await request.post(),而应使用request.post()

相关问题