Я пытаюсь загрузить изображение на сервер, но оно показывает ответ, подобный этому
ответ: {error = "Bad Request";message = "Обязательный параметр int 'customerId' отсутствует";path = "/ GroceryShoppingCartApplication / customer / uploadProfileImage";статус = 400;метка времени = "2018-09-19T04: 52: 03.849 + 0000";}
я искал так много ссылок, но моя проблема не решена. Пожалуйста, предложите мне правильный код.
Вот мой код:
func myImageUploadRequest()
{
let myUrl = NSURL(string: "myUrl.....");
let request = NSMutableURLRequest(url:myUrl! as URL);
request.httpMethod = "POST";
let headers = [
"content-type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
"Authorization": "bearer ff824d51-3c18-4efb-b6cf-70c33c78ac76",
"Cache-Control": "no-cache",
"Postman-Token": "8d576d32-1c29-f994-4337-b08e1aad60e9"
]
let param = [
"customerId":"3"
]
let boundary = generateBoundaryString()
let imageData = UIImageJPEGRepresentation(myImageView.image!, 1)
if(imageData==nil) { return; }
request.allHTTPHeaderFields = headers
request.httpBody = createBodyWithParameters(parameters: param, filePathKey: "imageFile", imageDataKey: imageData! as NSData, boundary: boundary) as Data
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
print("******* response = \(response)")
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("****** response data = \(responseString!)")
do {
let json = try JSONSerialization.jsonObject(with: data!, options: [])
print("response is :",json)
}catch
{
print(error)
}
}
task.resume()
}
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
let body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
print("getting key is:",key)
print("getting value is:",value)
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"; value=\"\(value)\"\r\n")
}
}
let filename = "user-profile.png"
let mimetype = "image/png"
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
body.append(imageDataKey as Data)
body.appendString(string: "\r\n")
body.appendString(string: "--\(boundary)--\r\n")
return body
}
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().uuidString)"
}
}
extension NSMutableData {
func appendString(string: String) {
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
append(data!)
}
}