gpt4 book ai didi

ios - 如何在iOS中将图像数据上传到服务器?

转载 作者:行者123 更新时间:2023-12-01 18:40:11 24 4
gpt4 key购买 nike

我想使用swift将图像数据存储在iOS中的服务器上。我试过下面的代码,但不能正常工作我必须做什么?

想要上传6张图片。 this is my controller view, after clicking save it want to store at server

func myImageUploadRequest()
{

let myUrl = NSURL(string: "http://easemyshop.in/upload_test/new.php");
//let myUrl = NSURL(string: "http://easemyshop.in/upload_test/new.php");

let request = NSMutableURLRequest(url:myUrl! as URL);
request.httpMethod = "POST";

let param = [


"tag" : "all",
"count" : "1",
"shopname" : "MayurShop",
"partyName" : "Paras",
"cur_date" : "14-06-2017",
"due_date" : "20-06-2017",
"karagir" : "Santra",
"remark" : "Urgent",
"order_status" : "Order Reccived"

/*
"firstName" : "Mayur",
"lastName" : "Shinde",
"userId" : "101"

*/
]

let boundary = generateBoundaryString()

request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")


let imageData = UIImageJPEGRepresentation((imageView?.image!)!, 1)

if(imageData==nil) { return; }

request.httpBody = createBodyWithParameters(parameters: param, filePathKey: "file", imageDataKey: imageData! as NSData, boundary: boundary) as Data

myActivityIndicator.isHidden = false
myActivityIndicator.startAnimating();

let task = URLSession.shared.dataTask(with: request as URLRequest)
{
data, response, error in

if error != nil
{
print("******** error=\(error)")
return
}

// You can print out response object
print("\n\n******* response *******\n\n")
print("\(response!)")
print("\n\n**************************\n\n")

// Print out reponse body
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)

print("\n\n****** response data *******\n\n")
print("\(responseString!)")
print("\n\n**************************\n\n")

do
{
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary

print("\n\n*************\n\n")
print(json!)
print("\n\n*************\n\n")

DispatchQueue.main.async(execute: {
self.myActivityIndicator.stopAnimating()
self.myActivityIndicator.isHidden = true
//self.imageView?.image = nil;
});

}
catch
{
print("\n\n*************ERROR******** => \(error)\n\n")
}

}

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

let filename = "user-profile.jpg"
let mimetype = "image/jpg"

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

最佳答案

func webServiceImageUploadForMyProfile(image:UIImage,url:String,method:HTTPMethod,parameters : [String:AnyObject]?,completionHandler:@escaping (JSON?,String)->Void) {

let url = try! URLRequest(url: url, method: .post, headers: nil)
Alamofire.upload(multipartFormData:{ multipartFormData in
if let imageData = UIImageJPEGRepresentation(image, 0.6) {
multipartFormData.append(imageData, withName: "image", fileName: "Profile.png", mimeType: "image/png")
}
for (key, value) in parameters! {
multipartFormData.append(value.data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
}, with: url, encodingCompletion: {
encodingResult in
switch encodingResult {
case .success(let upload, , ):
upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})
upload.responseJSON { response in
if(response.result.isSuccess){
if let data = response.result.value{
let json = JSON(data)
print(json)
completionHandler(json,String())
return
}
}else {
completionHandler(nil,(response.result.error?.localizedDescription)!)
}
}

case .failure( _):

break
}
})
}

请试试 ...

关于ios - 如何在iOS中将图像数据上传到服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44495551/

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