使用MultiFormData通过Alamofire上传图像

时间:2016-08-12 07:45:30

标签: ios swift image-uploading alamofire multipartform-data

我正在尝试使用服务器上传图片。 在Android中,它与这段代码完美配合:

RestTemplate restTemplate = new RestTemplate();

MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
String strPath = "D:\\Personal\\Projects\\Resources\\Images\\ic_flash_on.png";
Path path = Paths.get(strPath);
byte[] bytes = Files.readAllBytes(path);

map.add("id", 2);
map.add("file", new ByteArrayResource(bytes) {
  @Override
  public String getFilename() {
    return "ic_flash_on.png";
  }
});

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.add("Authorization", request.getHeader("Authorization"));

HttpEntity<MultiValueMap<String, Object>> imageEntity = new HttpEntity<MultiValueMap<String, Object>>(map, headers);
ResponseEntity<Photo> result = restTemplate.exchange("http://localhost:8080/api/photos/upload", HttpMethod.POST,
    imageEntity, Photo.class);
return result;

在iOS中,我使用Alamofire代码:

let url = HOST + "api/photos/upload"

    let accessToken = KeychainHelper.getStringForKey(KeychainConstaint.kAccessTokenKey) ?? ""
    let headers = [
        "Authorization": "Bearer \(accessToken)",
        "Content-Type": "multipart/form-data"
    ]

    Alamofire.upload(
        .POST,
        url,
        headers: headers,
        multipartFormData: { multipartFormData in
            var id = 10000
            let idData = NSData(bytes: &id, length: sizeof(Int))
            //multipartFormData.appendBodyPart(data: photo.data, name: "file")
            multipartFormData.appendBodyPart(data: idData, name: "id")
            multipartFormData.appendBodyPart(data: photo.data, name: "file", fileName: ".jpg", mimeType: "image/jpeg")
        },
        encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold) { encodingResult in
            switch encodingResult {
            case .Success(let upload, _, _):
                upload.responseJSON { response in
                    debugPrint(response)
                }
            case .Failure(let encodingError):
                print(encodingError)
            }
    }

它失败的原因是:&#34;必需的MultipartFile参数&#39; file&#39;不存在&#34;

我错过了什么吗? :(

1 个答案:

答案 0 :(得分:0)

let url = HOST + "api/photos/upload"

let accessToken = KeychainHelper.getStringForKey(KeychainConstaint.kAccessTokenKey) ?? ""
let headers = [
    "Authorization": "Bearer \(accessToken)",
    "Content-Type": "multipart/form-data"
]

var parameters = [String:AnyObject]()

var id = 10000
let idData = NSData(bytes: &id, length: MemoryLayout<Int>.size)

parameters = ["id":idData as AnyObject]

Alamofire.upload(multipartFormData: { multipartFormData in

    multipartFormData.append(photo.data , withName: "image" , fileName: ".jpeg", mimeType: "image/jpeg")
    // + sessionid + "/" + mobile
    for (key, value) in parameters {
        multipartFormData.append(value.data(using: String.Encoding.utf8.rawValue)!, withName: key)
    }

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


})