项目利用Alamofire上传文件,之前同事没注意考虑格式,造成图片上传不了问题。
上传文件格式如下:
let mimeTypes = ["png": "image/png",
"jpg": "image/jpg",
"jpeg": "image/jpeg",
"heic": "image/heic",
"heif": "image/heif",
"webp": "image/webp",
"tif": "image/tif",
"gif": "image/gif",
"mp4": "video/mp4",
"mov": "video/mov"]
刚开始后端同事不帮我们处理.heic格式的文件,那么就需要我们自己处理了,自己转一下格式再上传:
代码如下:
//其他格式也是一样
if suffix == "heic" || suffix == "heif" {
guard let newFileName = fileName.components(separatedBy: ".").first else {
break
}
let file1Data = try! Data(contentsOf: filePathUrl)
if let image: UIImage = UIImage(data: file1Data as Data) {
let twoData = image.jpegData(compressionQuality : 1.0)! as NSData
let newFileName = newFileName + ".jpeg"
formData.append(twoData as Data, withName: "files", fileName: newFileName , mimeType: "image/jpeg")
print("打印一下heic的图片名称----\(newFileName)")
}
}else{
formData.append(filePathUrl, withName: "files", fileName: fileName, mimeType: fileMimeType)
}
完整代码:
Alamofire.upload(multipartFormData: { (formData: MultipartFormData) -> Void in
for filePathUrl in paths {
guard let fileName = filePathUrl.absoluteString.components(separatedBy: "/").last,
let suffix = fileName.components(separatedBy: ".").last?.lowercased() else {
debugPrint("上传文件:获取文件名错误")
break
}
let mimeTypes = ["png": "image/png",
"jpg": "image/jpg",
"jpeg": "image/jpeg",
"heic": "image/heic",
"heif": "image/heif",
"webp": "image/webp",
"tif": "image/tif",
"gif": "image/gif",
"mp4": "video/mp4",
"mov": "video/mov"]
guard let fileMimeType = mimeTypes[suffix] else {
self.log.error("上传文件:获取mimeType错误")
print("上传文件:获取mimeType错误")
break
}
print("打印一下heic的图片名称----\(fileName)")
// formData.append(filePathUrl, withName: "files", fileName: fileName, mimeType: fileMimeType)
if suffix == "heic" || suffix == "heif" {
guard let newFileName = fileName.components(separatedBy: ".").first else {
break
}
let file1Data = try! Data(contentsOf: filePathUrl)
if let image: UIImage = UIImage(data: file1Data as Data) {
let twoData = image.jpegData(compressionQuality : 1.0)! as NSData
let newFileName = newFileName + ".jpeg"
formData.append(twoData as Data, withName: "files", fileName: newFileName , mimeType: "image/jpeg")
print("打印一下heic的图片名称----\(newFileName)")
}
}else{
formData.append(filePathUrl, withName: "files", fileName: fileName, mimeType: fileMimeType)
}
}
for (key, value) in body {
formData.append(value.data(using: .utf8)!, withName: key)
}
}, usingThreshold: 5, to: url, method: .post, headers: header, encodingCompletion: { result in
switch result {
}
})
这样就能自己转格式上传文件了
END.