无法附加文件数据以在Swift中上传多部分文件

时间:2020-07-06 09:24:42

标签: swift file-upload multipart

将文件附加到请求正文时遇到问题。无法读取文件数据。

致命错误::在展开可选值时意外发现nil:文件/home/user/Desktop/learn_swift/Sources/learn_swift/test.swift,第26行

import Foundation
import FoundationNetworking

let parameters = [
    [
        "key": "file",
        "src": "/home/user/Desktop/DM8.jpg",
        "type": "file"
    ]] as [[String : Any]]

let boundary = "Boundary-\(UUID().uuidString)"
var body = ""
var error: Error? = nil
for param in parameters {
    if param["disabled"] == nil {
        let paramName = param["key"]!
        body += "--\(boundary)\r\n"
        body += "Content-Disposition:form-data; name=\"\(paramName)\""
        let paramType = param["type"] as! String
        if paramType == "text" {
            let paramValue = param["value"] as! String
            body += "\r\n\r\n\(paramValue)\r\n"
        } else {
            let paramSrc = param["src"] as! String

            //ERROR OCCURS HERE...
            let fileData = try NSData(contentsOfFile:paramSrc, options:[]) as Data
            let fileContent = String(data: fileData, encoding: .utf8)!
            body += "; filename=\"\(paramSrc)\"\r\n"
              + "Content-Type: \"content-type header\"\r\n\r\n\(fileContent)\r\n"
        }
    }
}
body += "--\(boundary)--\r\n";
let postData = body.data(using: .utf8)

var request = URLRequest(url: URL(string: "http://localhost:8080/DruSight/drusightcontroller/processDocuments")!)
request.addValue("100056", forHTTPHeaderField: "docid")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("SessionToken=DruSight-65b5d5d8-0158-4b1c-a4f1-8915649911d9", forHTTPHeaderField: "Cookie")
request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

request.httpMethod = "POST"
request.httpBody = postData

let task = URLSession.shared.dataTask(with: request) { data, response, error in 
    guard let data = data else {
        print(String(describing: error))
        return
    }
    print(String(data: data, encoding: .utf8)!)
}

task.resume()

0 个答案:

没有答案