简体   繁体   中英

File upload using Swift Vapor 3.0

I'm trying to create a simple vapor service so I can upload video files (one at a time) through an api.

From my app I'm uploading the video file using Alamofire:

func uploadVideo(video: URL) {
    Alamofire.upload(videoFileURL, to: "http://localhost:8080/upload").responseString { response in
      debugPrint(response)
    }
}

The vapor controller method is like this (this is where I don't know how to do it):

func upload(_ req: Request) throws -> String {

  let data = try req.content.decode(Data.self).map(to: Data.self) { video in
    try Data(video).write(to: URL(fileURLWithPath: "/Users/eivindml/Desktop/video.mp4"))
    return Data(video)
  }

  return "Video uploaded";
}

How do I get the video file from the request and into the right format so I can write it do disk?

The method upload() is called correctly etc, as it works if I just have the last return statement.

Looking at your function it appears you're not handling your future response correctly, or extracting the data.

func upload(_ req: Request) throws -> Future<String> {
    return try req.content.decode(File.self).map(to: String.self) { (file) in
        try file.data.write(to: URL(fileURLWithPath: "/Users/eivindml/Desktop/\(file.filename)"))
        return "File uploaded"
    }
}

See if this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM