在Swift中使用参数上传图像

77

我正在尝试使用Swift上传带有参数的图像。当我尝试这段代码时,我可以获得参数但无法获得图像。

uploadFileToUrl(fotiño:UIImage){
    var foto =  UIImage(data: UIImageJPEGRepresentation(fotiño, 0.2))


    var request = NSMutableURLRequest(URL:NSURL(string: "URL"))
    request.HTTPMethod = "POST"

    var bodyData = "id_user="PARAMETERS&ETC""


    request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
    request.HTTPBody = NSData.dataWithData(UIImagePNGRepresentation(foto))
    println("miraqui \(request.debugDescription)")
    var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
    var HTTPError: NSError? = nil
    var JSONError: NSError? = nil

    var dataVal: NSData? =  NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error: &HTTPError)

    if ((dataVal != nil) && (HTTPError == nil)) {
        var jsonResult = NSJSONSerialization.JSONObjectWithData(dataVal!, options: NSJSONReadingOptions.MutableContainers, error: &JSONError)

        if (JSONError != nil) {
            println("Bad JSON")
        } else {
            println("Synchronous\(jsonResult)")
        }
    } else if (HTTPError != nil) {
        println("Request failed")
    } else {
        println("No Data returned")
    }
}

编辑2:

我认为我保存UIImage的路径存在问题,因为php告诉我该文件已经存在,我认为这是因为我发送了一个空白的文件。

func createRequest (#userid: String, disco: String, id_disco: String, pub: String, foto: UIImage) -> NSURLRequest {
    let param = [
        "id_user"  : userid,
        "name_discoteca"    : disco,
        "id_discoteca" : id_disco,
        "ispublic" : pub] // build your dictionary however appropriate

    let boundary = generateBoundaryString()

    let url = NSURL(string: "http....")
    let request = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "POST"
    request.timeoutInterval = 60
    request.HTTPShouldHandleCookies = false
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
    var imagesaver = ImageSaver()

    var image = foto  // However you create/get a UIImage
    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    let destinationPath = documentsPath.stringByAppendingPathComponent("VipKing.jpg")
    UIImageJPEGRepresentation(image,1.0).writeToFile(destinationPath, atomically: true)


    self.saveImage(foto, withFileName: "asdasd22.jpg")


    var path = self.documentsPathForFileName("asdasd22.jpg")


    self.ViewImage.image = self.loadImageWithFileName("asdasd22.jpg")



  //  let path1 = NSBundle.mainBundle().pathForResource("asdasd22", ofType: "jpg", inDirectory: path) as String! 

    **//path1 always crash**


    println(param.debugDescription)
    println(path.debugDescription)
    println(boundary.debugDescription)




    request.HTTPBody = createBodyWithParameters(param, filePathKey: "asdasd22.jpg", paths: [path], boundary: boundary)

    println(request.debugDescription)


    return request
}

你对 filePathKey 有什么问题?我也遇到了同样的问题。 - Amr Mohamed
简单上传图片...使用Alamofire - kalpesh jetani
3个回答

148

根据您在下面的评论中提供的信息,您正在使用$_FILES语法来检索文件。这意味着您想要创建一个multipart/form-data请求。该过程基本上是:

  1. 为您的multipart/form-data请求指定边界。

  2. 指定请求的Content-Type,以指定它是multipart/form-data并指定边界。

  3. 创建请求正文,将各个组件分开(每个发布的值以及每个上传之间)。

有关更多详细信息,请参见RFC 7578。无论如何,在Swift 3及更高版本中,这可能看起来像:

/// Create request
///
/// - parameter userid:   The userid to be passed to web service
/// - parameter password: The password to be passed to web service
/// - parameter email:    The email address to be passed to web service
///
/// - returns:            The `URLRequest` that was created

func createRequest(userid: String, password: String, email: String) throws -> URLRequest {
    let parameters = [
        "user_id"  : userid,
        "email"    : email,
        "password" : password]  // build your dictionary however appropriate
    
    let boundary = generateBoundaryString()
    
    let url = URL(string: "https://example.com/imageupload.php")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
    
    let fileURL = Bundle.main.url(forResource: "image1", withExtension: "png")!
    request.httpBody = try createBody(with: parameters, filePathKey: "file", urls: [fileURL], boundary: boundary)
    
    return request
}

/// Create body of the `multipart/form-data` request
///
/// - parameter parameters:   The optional dictionary containing keys and values to be passed to web service.
/// - parameter filePathKey:  The optional field name to be used when uploading files. If you supply paths, you must supply filePathKey, too.
/// - parameter urls:         The optional array of file URLs of the files to be uploaded.
/// - parameter boundary:     The `multipart/form-data` boundary.
///
/// - returns:                The `Data` of the body of the request.

private func createBody(with parameters: [String: String]? = nil, filePathKey: String, urls: [URL], boundary: String) throws -> Data {
    var body = Data()
    
    parameters?.forEach { (key, value) in
        body.append("--\(boundary)\r\n")
        body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
        body.append("\(value)\r\n")
    }
    
    for url in urls {
        let filename = url.lastPathComponent
        let data = try Data(contentsOf: url)
        
        body.append("--\(boundary)\r\n")
        body.append("Content-Disposition: form-data; name=\"\(filePathKey)\"; filename=\"\(filename)\"\r\n")
        body.append("Content-Type: \(url.mimeType)\r\n\r\n")
        body.append(data)
        body.append("\r\n")
    }
    
    body.append("--\(boundary)--\r\n")
    return body
}

/// Create boundary string for multipart/form-data request
///
/// - returns:            The boundary string that consists of "Boundary-" followed by a UUID string.

private func generateBoundaryString() -> String {
    return "Boundary-\(UUID().uuidString)"
}

和:

extension URL {
    /// Mime type for the URL
    ///
    /// Requires `import UniformTypeIdentifiers` for iOS 14 solution.
    /// Requires `import MobileCoreServices` for pre-iOS 14 solution

    var mimeType: String {
        if #available(iOS 14.0, *) {
            return UTType(filenameExtension: pathExtension)?.preferredMIMEType ?? "application/octet-stream"
        } else {
            guard
                let identifier = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(),
                let mimeType = UTTypeCopyPreferredTagWithClass(identifier, kUTTagClassMIMEType)?.takeRetainedValue() as String?
            else {
                return "application/octet-stream"
            }

            return mimeType
        }
    }
}

extension Data {
    
    /// Append string to Data
    ///
    /// Rather than littering my code with calls to `data(using: .utf8)` to convert `String` values to `Data`, this wraps it in a nice convenient little extension to Data. This defaults to converting using UTF-8.
    ///
    /// - parameter string:       The string to be added to the `Data`.
    
    mutating func append(_ string: String, using encoding: String.Encoding = .utf8) {
        if let data = string.data(using: encoding) {
            append(data)
        }
    }
}

有了这一切,现在您需要提交此请求。我建议以异步方式完成。例如,使用URLSession ,您可以执行以下操作:

let request: URLRequest

do {
    request = try createRequest(userid: userid, password: password, email: email)
} catch {
    print(error)
    return
}

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        // handle error here
        print(error ?? "Unknown error")
        return
    }
    
    // parse `data` here, then parse it
    
    // note, if you want to update the UI, make sure to dispatch that to the main queue, e.g.:
    //
    // DispatchQueue.main.async {
    //     // update your UI and model objects here
    // }
}
task.resume()

如果您要上传大型资源(例如视频或类似物),您可能希望使用上述的基于文件的排列方式。请参见https://dev59.com/Hm4NtIcB2Jgan1znRxD2#70552269


有关Swift 2版本,请参见此答案的先前版本


我尝试了很多保存图像到本地的方法...让documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String。我可以保存它,但是当我尝试上传时,PHP告诉我已经存在,我认为我发送了空白图像或者出了些问题...我想我在路径和filePathKey之间感到困惑,我编辑了我的答案! - Pedro Manfredi
顺便说一下,选择 NSSearchPathForDirectoriesNSBundle 是指定要上传的本地文件的方式。但是,如果您从服务器收到“已存在”的消息,则与此无关。 “已存在”表示 服务器 有一个同名的文件副本(显然脚本编写为不会覆盖它)。 - Rob
4
这是 Swift 2 的代码。根据 mimeTypeForPath 的注释,你需要使用 MobileCoreServices 库。因此,在文件顶部处添加 import MobileCoreServices 即可。 - Rob
1
@luke - 这是一个看法问题,但感觉客户端应用程序与后端架构的实现细节有点纠缠在一起。您还可能要处理两个身份验证系统和两个故障点。我可能会倾向于为应用程序使用单个端点,并让Web服务管理图像存储。 - Rob
1
@KrutikaSonawala - 在此之前,我假設您有一個編寫 JSON 響應的 Web 服務。這是讓 Web 服務返回可解析響應給客戶端應用程序的最強大方法之一。也許您的 Web 服務沒有設計成返回 JSON 響應。或者你的 Web 服務出現了錯誤,阻止它創建適當的 JSON 響應。我無法根據您的評論進行診斷。如果上述內容不清楚,建議您發布自己的問題,向我們展示您所做的事情、期望得到的響應以及實際收到的響應。 - Rob
显示剩余20条评论

14

AlamoFire现在支持多部分表单:

https://github.com/Alamofire/Alamofire#uploading-multipartformdata

这篇博客文章提供了一个示例项目,介绍如何在AlamoFire中使用Multipart。

http://www.thorntech.com/2015/07/4-essential-swift-networking-tools-for-working-with-rest-apis/

相关代码可能看起来像这样(假设你正在使用Alamofire和SwiftyJSON):

func createMultipart(image: UIImage, callback: Bool -> Void){
    // use SwiftyJSON to convert a dictionary to JSON
    var parameterJSON = JSON([
        "id_user": "test"
    ])
    // JSON stringify
    let parameterString = parameterJSON.rawString(encoding: NSUTF8StringEncoding, options: nil)
    let jsonParameterData = parameterString!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
    // convert image to binary
    let imageData = UIImageJPEGRepresentation(image, 0.7)
    // upload is part of AlamoFire
    upload(
        .POST,
        URLString: "http://httpbin.org/post",
        multipartFormData: { multipartFormData in
            // fileData: puts it in "files"
            multipartFormData.appendBodyPart(fileData: jsonParameterData!, name: "goesIntoFile", fileName: "json.txt", mimeType: "application/json")
            multipartFormData.appendBodyPart(fileData: imageData, name: "file", fileName: "iosFile.jpg", mimeType: "image/jpg")
            // data: puts it in "form"
            multipartFormData.appendBodyPart(data: jsonParameterData!, name: "goesIntoForm")
        },
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .Success(let upload, _, _):
                upload.responseJSON { request, response, data, error in
                    let json = JSON(data!)
                    println("json:: \(json)")
                    callback(true)
                }
            case .Failure(let encodingError):
                callback(false)
            }
        }
    )
}

let fotoImage = UIImage(named: "foto")
    createMultipart(fotoImage!, callback: { success in
    if success { }
})

2

谢谢@Rob,您的代码很好用,但在我的情况下,我正在从相册中检索图像,并使用以下代码获取图像名称:

let filename = url.lastPathComponent

但是这段代码将图片扩展名显示为 .JPG(大写字母),但服务器不接受大写字母的扩展名,因此我修改了我的代码:

 let filename =  (path.lastPathComponent as NSString).lowercaseString

现在我的代码运行良好。

谢谢你 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接