gpt4 book ai didi

ios - 如何使用 Alamofire 在请求正文中上传图像文件?

转载 作者:行者123 更新时间:2023-11-29 00:26:11 24 4
gpt4 key购买 nike

我是 iOS 开发的新手,现在我正在编写一个使用 Alamofire 将图像上传到服务器的应用程序,但在寻找解决方案和阅读文档数小时后,我仍然没有让它工作。有人可以帮忙吗?谢谢。到目前为止,这是我的代码:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
imagePicker.dismiss(animated: true, completion: nil)

//Upload image from here
//Get user for header info
var user = User.getUserInstance()

//Get current patient for header info
var currentPatient = CurrentPatient.getCurrentPatientInstance()

//Server address
let serverAddress = user.serverAddress

//Prep for headers
var headers = [
"ISHC_LOGIN": user.username,
"ISHC_PWD": user.password,
"ISHC_API_TOKEN":"token",
"ISHC_OPERATION":"CreateImage",
"ISHC_IMAGE_NAME":"test",
"ISHC_EXTAPP_ID":"app",
"ISHC_FOLDER_ID":currentPatient.getCurrentPatient().patientID,
"ISHC_EXTAPP_VALUE":"IS_WEB_STAGE",
"Accept-Encoding": "application/xml"
]

print("UPLOADING...")

let request = Alamofire.upload(multipartFormData: { multipartFormData in
let imageData = UIImagePNGRepresentation(image)
multipartFormData.append(imageData!, withName: "image", fileName: "file.png", mimeType: "image/png")
// multipartFormData.append((value.data(using: .utf8))!, withName: key)

}, to: serverAddress, method: .post, headers: headers,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { [weak self] response in
guard let strongSelf = self else {
return
}
debugPrint("RESPONSE IS:\(response)")
}
case .failure(let encodingError):
print("error:\(encodingError)")
}
})
debugPrint("request is:\(request)")
}

基于API(我只是前端开发),我可以使用请求体上传图像并且可以保持图像文件原样(不需要编码),但我不确定使用multipartFormData.append 是一个正确的解决方案。此外,当我尝试打印请求时,我没有看到整个 curl 命令。

最佳答案

尝试将 UIImagePickerController 选中的图片保存到目录中

    func saveUserProfileAtDirectory (userImage : UIImage) -> NSURL {

let documentsDirectoryURL = try! NSFileManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
// create a name for your image
let imageURL = documentsDirectoryURL.URLByAppendingPathComponent("pic.jpg")

if NSFileManager.defaultManager().fileExistsAtPath(imageURL.path!) {

do {
try NSFileManager.defaultManager().removeItemAtPath(imageURL.path!)
}
catch
{

}
}

if UIImageJPEGRepresentation(userImage, 1.0)!.writeToFile(imageURL.path!, atomically: true) {

return imageURL

} else {
print("error saving file")
}

return NSURL()

}

然后在almofire中使用imageURL:

multipartFormData.appendBodyPart(fileURL: imageURL, name: "ISHC_IMAGE_NAME")

关于ios - 如何使用 Alamofire 在请求正文中上传图像文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42962725/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com