本文介绍了如何在多部分http发布请求中发布图像数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想上传图片数组,我应该如何将array附加到NSMutableData.这是我的代码

I want to upload array of images, how should I append array to NSMutableData. here is my code

func createBodyWithParametersMulti(parameters: [String: String]?, filePathKey: String?, imageDataKey: [NSData?], boundary: String) -> NSData {
        let body = NSMutableData();

        if parameters != nil {
            for (key, value) in parameters! {
                body.appendString("--\(boundary)\r\n")
                body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString("\(value)\r\n")
            }
        }

        if(imageDataKey.count != 0){
            let filename=filePathKey as! String
            // let mimetype = "image/jpeg"

            body.appendString("--\(boundary)\r\n")
            body.appendString("Content-Disposition: form-data; name=\"\(filename)\"; filename=\"image.jpg\"\r\n")
            // body.appendString("Content-Disposition: form-data; name=\"image\"; filename=\"image.jpg\"\r\n")
            body.appendString("Content-Type: \("image.jpeg")\r\n\r\n")


            body.append(imageDataKey[0]! as Data)
               body.appendString("\r\n")
           }
        else {

        }
        body.appendString("--\(boundary)--\r\n")

        return body
    }

ImageDataKey 是包含多个图像作为 NSDataarray 的名称.

ImageDataKey is the name of the array containing multiple images as a NSData.

推荐答案

试试这个

func createBodyWithParametersAndImages(parameters: [String: Any]?, filePathKey: [String], imageDataKey: [Data], boundary: String) -> NSData {
    let body = NSMutableData();

    if parameters != nil {
        for (key, value) in parameters! {
            body.appendString(string: "--\(boundary)\r\n")
            body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
            body.appendString(string: "\(value)\r\n")
        }
    }

    for index in 0..<imageDataKey.count {
        let data = imageDataKey[index]

        let filename = "image.jpeg"
        let mimetype = "image/jpeg"

        body.appendString(string: "--\(boundary)\r\n")
        body.appendString(string: "Content-Disposition: form-data; name=\"\(filePathKey[index])\"; filename=\"\(filename)\"\r\n")
        body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
        body.append(data)
        body.appendString(string: "\r\n")

    }


    body.appendString(string: "--\(boundary)--\r\n")

    return body
}

方法调用

let body = createBodyWithParametersAndImages(parameters: parameter, filePathKey: ["profile_image", "cover_image"], imageDataKey: [imageData1, ImageData2] as! [NSData], boundary: boundary) as Data
request.httpBody = body

这篇关于如何在多部分http发布请求中发布图像数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 05:27