0

我想使用 Alamofire 将图片上传到服务器。

我已将所选照片从 imagePicker 更改为 jpegData,并将其用于 MultipartFormData 的追加。

发送通信时,应用程序的内存迅速增加,而使用 debugPrint 时,会提取大量代码。

问题是什么?

我把我的代码放在下面。

let header: HTTPHeaders = [
        "Content-Type":"multipart/form-data; boundary=\(boundary)",
        "access_token":"\(UserDefaults.standard.string(forKey: "token")!)"
    ]

    AF.upload(multipartFormData: { (MultipartFormData) in

        MultipartFormData.append(self.imageData, withName: "img", fileName: "img", mimeType: "img/jpeg")
        MultipartFormData.append((self.titleTextField.text?.data(using: .utf8))!, withName: "content")
    }, to: "https://httpbin.org/post", method: .post, headers: header).responseJSON { (result) in
            debugPrint(result)

    }


func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    guard let pickedImage = info[.originalImage] as? UIImage else { return }
    imageView.image = pickedImage
    image = pickedImage
    imageData = pickedImage.jpegData(compressionQuality: 0)
    imageViewNilLbl.isHidden = true
    picker.dismiss(animated: true, completion: nil)
}

在此处输入图像描述

4

1 回答 1

0

我使用了这种方法,在我的情况下一切正常。像这样试试。

public func upload(method: HTTPMethod = .post, endpoint: String, params: NSDictionary? = nil, image: UIImage) {

    let url = BaseUrl.url + endpoint

    AF.upload(multipartFormData: { multipartFormData in
        if let params = params {
            for (key, value) in params {
                guard let data = "\(value)".data(using: String.Encoding.utf8) else { continue }
                multipartFormData.append(data, withName: key as? String ?? "")
            }
        }

        // Append image
        attachDataToMultipart(file: image.jpegData(compressionQuality: 0.5), withName: "file", fileType: .photo, multipartFormData: multipartFormData, mimeType: .photo)
    }, to: url, method: method, headers: nil).responseJSON { (result) in
        debugPrint(result)
    }
}

func attachDataToMultipart(file: Data?, withName: String, fileType: UploadRequestFileTypeEnum, multipartFormData: MultipartFormData, mimeType: UploadMimeTypeEnum) {
    guard let data = file else { return }
    let name = UUID().uuidString + fileType.rawValue
    multipartFormData.append(data, withName: withName, fileName: name, mimeType: mimeType.rawValue)
}

enum UploadRequestFileTypeEnum: String {
    case photo = ".jpg"
    case video = ".mov"
    case file = "pdf"
}

enum UploadMimeTypeEnum: String {
    case photo = "image/jpg"
    case video = "video/quicktime"
    case file = "application/pdf"
}
于 2020-07-02T08:35:25.003 回答