gpt4 book ai didi

node.js - 将图像上传到 Node.js Express 服务器 Swift

转载 作者:行者123 更新时间:2023-11-28 12:21:56 25 4
gpt4 key购买 nike

我目前正在创建一个应用程序,我将在其中使用 multer 中间件将图像从 iOS 设备发送到我的 expressjs 服务器。我已经设置了服务器端,但我相信我在客户端有错误,因为我无法让我的 POST 请求正常工作。这是我的快速代码。

        class func changeChannelImage(handle: String, imageURL: URL, completionHandler: @escaping (Int?, Error?) -> Void){
let baseURL = "http://10.0.0.220:3000/channel/channelImage?handle=\(handle)"

func createRequestBodyWith(parameters:[String:NSObject], boundary:String) -> Data{

var body = Data()

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")
}

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

var mimetype = "image/png"

let defFileName = "channelImage.png"
print(imageURL.absoluteString)
do {
var data = try Data(contentsOf: imageURL) //Image file URL in device's directory
var image = UIImage(data: data)

let imageData = UIImagePNGRepresentation(image!)

body.appendString(string: "Content-Disposition: form-data; filename=\"\(defFileName)\"\r\n")
print("Content-Type: \(mimetype)\r\n\r\n")
body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
body.append(imageData!)
body.appendString(string: "\r\n")

body.appendString(string: "--\(boundary)--\r\n")
}
catch {
print(error.localizedDescription)
}

return body
}
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().uuidString)"
}

var request = URLRequest(url: URL(string: baseURL)!)
request.httpMethod = "POST"
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.httpBody = createRequestBodyWith(parameters: [:], boundary: generateBoundaryString())


let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
if error == nil {
let res = response as! HTTPURLResponse
let code = res.statusCode
if code != 200 {
print(String(data: data!, encoding: .utf8))
}
DispatchQueue.main.async {
completionHandler(code, nil)
}
}
else {
print(error!)
DispatchQueue.main.async {
completionHandler(0, error)
}

}
}
task.resume()

}

有谁知道为什么服务器无法正确读取图像文件?任何帮助将不胜感激。

最佳答案

将你的图片数据转换成base64字符串然后追加到body中

关于node.js - 将图像上传到 Node.js Express 服务器 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44535431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com