python iOS -无法将视频文件从Swift上传到FastAPI服务器

waxmsbnn  于 2022-11-21  发布在  Python
关注(0)|答案(1)|浏览(125)

我从this question获取了上传视频文件的代码;但是会发生错误。
下面是从相册中选择视频的代码:

var videoURL: URL?

extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        picker.dismiss(animated: true, completion: nil)
        if let pickedVideo = info[UIImagePickerController.InfoKey.mediaURL] as? URL {
            videoURL = pickedVideo
}

这是将视频上传到服务器的代码。
第一次
以下是FastAPI服务器代码:

from fastapi import FastAPI, File, UploadFile
from typing import List
import os

app = FastAPI()

@app.get("/")
def read_root():
  return { "Hello": "World" }

@app.post("/files/")
async def create_files(files: List[bytes] = File(...)):
    return {"file_sizes": [len(file) for file in files]}

@app.post("/uploadfiles")
async def create_upload_files(files: List[UploadFile] = File(...)):
    print('here')
    UPLOAD_DIRECTORY = "./"
    for file in files:
        contents = await file.read()
        with open(os.path.join(UPLOAD_DIRECTORY, file.filename), "wb") as fp:
            fp.write(contents)
        print(file.filename)
    return {"filenames": [file.filename for file in files]}

这是错误:

INFO:     127.0.0.1:65191 - "POST /uploadfiles HTTP/1.1" 422 Unprocessable Entity
huus2vyu

huus2vyu1#

您正在尝试发送multipart/form-data(请参阅FastAPI documentation for uploading Files),但您已将Content-Type标头设置为application/json。因此,您应该删除/更改它。
另外,在客户端,您应该使用与服务器端相同的form密钥来上传文件,即files(因为您将其定义为files: List[bytes] = File(...)),而不是videoThis answer演示了如何将单个或多个文件上传到FastAPI服务器。请查看它。

相关问题