Swift-具有和不具有图像的多部分/表单数据POST请求(上传)

时间:2019-04-08 17:27:53

标签: ios swift file-upload swift4 multipartform-data

我正在尝试下面的代码来上传没有图片的个人资料数据,并收到400错误请求。而且,当我上传带有文件图像的profiledata时出现同样的错误。

某些格式不匹配,请帮忙!!!

Postman Request Image

var body = NSMutableData()
body.append("Content-Disposition: form-data; name=\"profileData\"".data(using: String.Encoding.utf8)!)
body.append("\(inputStr)\r\n".data(using: String.Encoding.utf8, allowLossyConversion: true)!)
body.append("Content-Disposition: form-data; name=\"file\"".data(using: String.Encoding.utf8)!)
body.append("\("")\r\n".data(using: String.Encoding.utf8, allowLossyConversion: true)!)
request.httpBody = body as Data

1 个答案:

答案 0 :(得分:0)

request.httpMethod = "POST"
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
        let body = NSMutableData()
        body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)




        let strPhotoUrl = photourl
        let mimetype = "image/jpeg"
        let readPath = Utility.getPhotofolder().stringByAppendingPathComponent(pathComponent:strPhotoUrl) // pass the path of the image 



        let image    = UIImage(named: strPhotoUrl)
        if (image == nil)
        {
            print("image is nil")
            return
        }
        let image_data = UIImagePNGRepresentation(image!)
        if(image_data == nil)
        {   
            return
        }

        body.append("Content-Disposition:form-data; name=\"attachedImage\"; filename=\"\(photourl)\"\r\n".data(using: String.Encoding.utf8)!)
        body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
        body.append(image_data!)

        body.append("\r\n".data(using: String.Encoding.utf8)!)

        body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)

        request.httpBody = body as Data