【问题标题】:Swift - multipart/form-data POST request(upload) with and without imageSwift - 带和不带图像的多部分/表单数据 POST 请求(上传)
【发布时间】:2019-08-29 21:59:01
【问题描述】:

我正在尝试使用以下代码上传不带图像的配置文件数据并收到 400 个错误请求。而且,当我上传带有文件图像的配置文件数据时,也会出现同样的错误。

有些格式不匹配请帮忙!!!

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

【问题讨论】:

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


    【解决方案1】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-17
      • 2016-06-29
      • 1970-01-01
      • 1970-01-01
      • 2015-01-25
      • 2012-11-27
      • 1970-01-01
      相关资源
      最近更新 更多