Swift UrlSession多部分/表单数据上传图像数组

1cklez4t  于 2023-01-01  发布在  Swift
关注(0)|答案(1)|浏览(171)

与 NodeJS 后端我有以下函数来接收图像数组,这是测试与 Postman 和它的工作正常,并返回上传的数组细节,

router.post('/imagesTest',multer().fields([{ name: 'externalImages', maxCount: 10 }]),adminController.imagesTest)

exports.imagesTest = async (req, res) => {
  console.log(req.files['externalImages'])
  res.send(req.files['externalImages'])
};

现在我想用swift发送图像,使用以下命令,

func imagesTest(imageDataArray : [Data]) -> AnyPublisher<APIResponse, Error> {
        print("================= TEST IMAGES ")
        let boundary = UUID().uuidString
        var request = URLRequest(url: URL(string: "\(Constants.baseUrl)/admin/imagesTest")!)
        request.httpMethod = "POST"
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
        request.httpBody = createMultiImageMultiPartBody(boundary: boundary, imageDataArray: imageDataArray)
        return URLSession.shared.dataTaskPublisher(for: request)
            .receive(on: RunLoop.main)
            .map({$0.data})
            .decode(type: APIResponse.self, decoder: JSONDecoder())
            .eraseToAnyPublisher()
    }

func createMultiImageMultiPartBody(boundary : String,imageDataArray : [Data]) -> Data {
            var body = Data()
    
            let mimetype = "image/jpg"
            
            for imageData in imageDataArray{
                body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
                body.append("Content-Disposition: form-data; name=\"externalImages\"; filename=\"\(Date().timeIntervalSince1970).jpg\"\r\n".data(using: String.Encoding.utf8)!)
                body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
                body.append(imageData)
                body.append("\r\n".data(using: String.Encoding.utf8)!)
                body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
            }
            return body
        }

但不幸的是,我只得到1图像在后端!!为什么呢?我搜索了很多,我发现这个问题以及same issue
注意:我不想使用任何第三方库
任何帮助都将不胜感激

kknvjkwl

kknvjkwl1#

我通过检查 Postman 请求正文发现了我的代码的错误,createMultiImageMultiPartBody函数应该如下所示,希望能对大家有所帮助

func createMultiImageMultiPartBody(boundary : String,imageDataArray : [Data]) -> Data {
            var body = Data()
    
            let mimetype = "image/jpg"
            
            for imageData in imageDataArray{
                body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
                body.append("Content-Disposition: form-data; name=\"externalImages\"; filename=\"\(Date().timeIntervalSince1970).jpg\"\r\n".data(using: String.Encoding.utf8)!)

                body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
                body.append(imageData)
                body.append("\r\n".data(using: String.Encoding.utf8)!)
                
            }
            // Just take this line out of the images loop 
            body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
            return body
        }

相关问题