2

如何在 Swift With Moya 中使用 multipart/form-data 上传图像

我的代码

var multipartBody: [MultipartFormData]? {
    switch self {
    case .registerWith(let registrationObject ):
        if let profileImageData = registrationObject.profileImageData{
        return [MultipartFormData(provider: .data(profileImageData), name: "profile_picture", fileName: "\(registrationObject.phone).jpg",
            mimeType: "image/jpeg")]
        }
        return nil
    default:
        return nil
    }
}

var task: Task {
    switch self {
    case .registerWith:
        if let multipartBody = multipartBody {
            return .upload(.multipart(multipartBody))
        }else{
            return .request
        }
    default:
        return .request
    }
}

但我需要使用键“profileImage”在正文中发送 imageData

4

3 回答 3

6

使用 Moya 10.0.0 及更高版本在 Multipart 中上传图像

1- 将要上传的文件放入 MultipartFormData 数组

// put files in MultipartFormData Arry  
   var multipartBody :[Moya.MultipartFormData]?{
    switch self {
    case .registerWith(let imageData , let name ,let description  ):
        // any additional body data or body parms
        let nameDataProvider = MultipartFormData(provider: .data(name.data(using: .utf8)!), name: "name")
        let emailDataProvider = MultipartFormData(provider: .data(email.data(using: .utf8)!), name: "email")
        // image want to upload it or file as a MultipartFormData
        let imageDataProvider = Moya.MultipartFormData(provider: MultipartFormData.FormDataProvider.data(imageData), name: "avatar", fileName: "photo.jpg", mimeType: "image/jpeg")
            return [ imageDataProvider , descriptionDataProvider ]
    default:
        return []
    }
}

2-使此方法的任务类型为uploadMultipart

var task: Task {
    switch self {
    case .registerWith:
        // for each method multi part use its multipartBody that declared it in step one needed
        return .uploadMultipart(multipartBody!)
    default:
        guard let parameters = self.parameters else {
            return .requestPlain
        }
        return .requestParameters(parameters: parameters.values, encoding: parameters.encoding)
    }
}

使用 Moya 9.0.0 及以下版本在 Multipart 中上传图像

1- 将要上传的文件放入 MultipartFormData 数组

// put files in MultipartFormData Arry  
var multipartBody: [MultipartFormData]? {
     switch self {
          case .registerWith(let imageData , let name ,let description  ):
              return [MultipartFormData(provider: .data(imageData),
             name: "profile_picture", fileName: "fileName", mimeType: "image/jpeg")]
              default:
               return nil
       } 
}

2-将 multipartBody 的提供者添加到您需要的方法的请求正文中

var parameters: [String: Any]? {
     switch self {
          case .registerWith(let registrationObject ):
          var body = registrationObject.toJSON()!
          // add the file in body 
          body["profile_picture"] = multipartBody?[0].provider
          return body
     }
}

3-使此方法的任务类型为上传

var task: Task {
       switch self {
           case .registerWith:
              //  multipartBody that in First step
             return .upload(.multipart(multipartBody))
        }
}
于 2017-12-08T21:47:09.413 回答
4

听到是在 swift 4.2 中使用 Moya 上传图像的代码

1)在moya的任务部分改变如下功能

var task: Task {
        switch self {

        case .signup(let params):
            var formData = [MultipartFormData]()
            for (key, value) in params {
                if let imgData = value as? Data {
                    formData.append(MultipartFormData(provider: .data(imgData), name: key, fileName: "testImage.jpg", mimeType: "image/jpeg"))
                } else {
                    formData.append(MultipartFormData(provider: .data("\(value)".data(using: .utf8)!), name: key))
                }
            }
            return .uploadMultipart(formData)

        case .signIn(let params), .resetPassword(let params), .changePassword(let params), .socialLogin(let params):
            return .requestParameters(parameters: params, encoding: URLEncoding.default)
        }
    }

2)如何制作参数

        var params = [String:Any]()
        params["first_name"] = self.txtFirstName.text
        params["last_name"] = self.txtLastName.text
        params["email"] = self.txtEmailAddess.text
        params["password"] = self.txtPassword.text

        if self.imgProfilePic.image != nil {
            if let imgData:Data = self.imgProfilePic.image!.pngData() {
                params["picture"] = imgData
            }
        }
        else {
           params["picture"] = ""
        }

并进一步将此参数传递给 API 调用。

于 2018-02-21T13:04:04.920 回答
-3

您需要将“名称:“profile_picture””更改为“名称:“profileImage””,试试这个。

于 2017-11-28T12:49:35.597 回答