简体   繁体   English

swift3-将图像上传到Web服务器

[英]swift3 - uploading image to webserver

I am trying to upload an image that is chosen from a UIImagePickerController to my web server hosted on AWS. 我正在尝试将从UIImagePickerController中选择的图像上传到托管在AWS上的Web服务器。 I am following this tutorial: https://www.udemy.com/swift-php-mysql-user-sign-up-sign-in-sign-out-and-more/learn/v4/overview and I am getting a bunch of Argument labels '(_:)' do not match any available overloads errors. 我正在学习本教程: https : //www.udemy.com/swift-php-mysql-user-sign-up-sign-in-sign-out-and-more/learn/v4/overview ,我得到了一堆Argument labels '(_:)' do not match any available overloads错误。 I've tried searching this error but I havent found anything that relates to my current code. 我尝试搜索此错误,但未找到与当前代码相关的任何内容。 I'm not using the original code in the tutorial, I'm trying to translate it to Swift3 and use the following answer: iOS swift NSMutableData has no member appendString to follow best coding practices. 我没有在教程中使用原始代码,而是尝试将其转换为Swift3并使用以下答案: iOS swift NSMutableData没有成员appendString可以遵循最佳编码实践。 Here is my current code: 这是我当前的代码:

func createBodyWithParameters(_ parameters: [String: String]?, filePathKey: String?, imageDataKey: Data, boundary: String) -> Data {
        var body = Data();

        if parameters != nil {
            for (key, value) in parameters! {
                body.append(Data("--\(boundary)\r\n"))
                body.append(Data("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n"))
                body.append(Data("\(value)\r\n"))
            }
        }

        let filename = "user-profile.jpg"

        let mimetype = "image/jpg"

        body.append(Data("--\(boundary)\r\n"))
        body.append(Data("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n"))
        body.append(Data("Content-Type: \(mimetype)\r\n\r\n"))
        body.append(imageDataKey)
        body.append(Data("\r\n"))



        body.append(Data("--\(boundary)--\r\n"))

        return body as Data
    }

Can someone explain what I'm doing wrong? 有人可以解释我在做什么错吗? Thanks! 谢谢!

You cannot initialize Data like this: 您不能像这样初始化数据:

Data("foo")

What you can do is: 您可以做的是:

Data("foo".utf8)

Like in the link you provided. 就像在您提供的链接中一样。 (You are missing the .utf8) (您缺少.utf8)

EDIT: Yes the guy said he didn't want to use that code, but hear me out, this version of the extension doesn't allow lossy connection, and as long as you write anything inside the string, data will never be nil. 编辑:是的,那个家伙说他不想使用该代码,但是请听我说,此扩展名版本不允许有损连接,只要您在字符串中编写任何内容,数据就永远不会为零。

extension NSMutableData {
   func appendString(_ string: String) {
        let data = string.data(using: String.Encoding.utf8, allowLossyConversion: false)
        append(data!)
    }
}

Usage: 用法:

body.appendString("foo")

Just initialize body like this: 像这样初始化body:

var body = NSMutableData()

And return like this 然后像这样返回

return body as Data

Try this code. 试试这个代码。 You can use this code for uploading images to webserver in swift3 您可以使用此代码在swift3中将图像上传到网络服务器

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

func photoDataToFormData(parameters: [String: String]?, data: Data, boundary:String, fileName:String) -> Data
{
    var fullData = Data()

    if parameters != nil {
        for (key, value) in parameters! {

            print ("Key: \(key), Value: \(value)")
            let str = "--\(boundary)\r\n" + "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n" + "\(value)\r\n"
            let data = str.data(using: String.Encoding.utf8, allowLossyConversion: true)

            fullData.append(data!)
        }
    }

    // 1 - Boundary should start with --
    let lineOne = "--" + boundary + "\r\n"
    fullData.append(lineOne.data(using: String.Encoding.utf8, allowLossyConversion: false)!)

    // 2
    let lineTwo = "Content-Disposition: form-data; name=\"image\"; filename=\"" + fileName + "\"\r\n"
    NSLog(lineTwo)
    fullData.append(lineTwo.data(using: String.Encoding.utf8, allowLossyConversion: false)!)

    // 3
    let lineThree = "Content-Type: image/jpg\r\n\r\n"
    fullData.append(lineThree.data(using: String.Encoding.utf8, allowLossyConversion: false)!)

    // 4
    fullData.append(data)

    // 5
    let lineFive = "\r\n"
    fullData.append(lineFive.data(using: String.Encoding.utf8, allowLossyConversion: false)!)

    // 6 - The end. Notice -- at the start and at the end
    let lineSix = "--" + boundary + "--\r\n"
    fullData.append(lineSix.data(using: String.Encoding.utf8, allowLossyConversion: false)!)
    return fullData
}

After the above code you need to call a function before the task in the Api function. 在上面的代码之后,您需要在Api函数中的任务之前调用一个函数。 I have mention that code below. 我在下面提到了该代码。

 let imageData = UIImageJPEGRepresentation(profileImage.image!, 0.5)

 let boundary = generateBoundaryString()

 let fullData = photoDataToFormData(parameters: parameters as? [String : 
 String], data: imageData!, boundary: boundary, fileName: "Test.jpg")

 request.setValue("multipart/form-data; boundary=" + boundary, 
 forHTTPHeaderField: "Content-Type")

    // REQUIRED!
 request.setValue(String(fullData.count), forHTTPHeaderField: "Content-
 Length")

 request.httpBody = fullData

I has solved This problem in swift 4 by adding the following lines after class ViewController: 通过在类ViewController之后添加以下行,我已经在Swift 4中解决了这个问题:

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

extension NSMutableData {
    func appendString(string: String) {
        let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
        append(data!)
    }
}

I mean class Viewcontroller the class that created when you add ViewController to your project. 我是说Viewcontroller类是将ViewController添加到项目中时创建的类。 example next class: 下一个类别的示例:

   class ViewController2: UIViewController ,UINavigationControllerDelegate , UIImagePickerControllerDelegate{
      // my code
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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