如何使用 Swift 将多张图片上传到服务器?
Posted
技术标签:
【中文标题】如何使用 Swift 将多张图片上传到服务器?【英文标题】:How to upload multiple images to server using Swift? 【发布时间】:2016-11-03 13:55:50 【问题描述】:fun UploadRequest()
if (photoArray.count > 0)
for var i=0 ; i < photoArray.count; i++
print(photoArray)
let image = (photoArray[i] as? UIImage)!
let imageData = UIImagePNGRepresentation(image)
if imageData != nil
let request = NSMutableURLRequest(URL: NSURL(string:"MY_URL")!)
_ = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
let boundary = NSString(format: "---------------------------14737809831466499882746641449")
let contentType = NSString(format: "multipart/form-data; boundary=%@",boundary)
request.addValue(contentType as String, forHTTPHeaderField: "Content-Type")
let body = NSMutableData()
body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format:"Content-Disposition: form-data; name=\"profile_photo\"; filename=\"(Image_Name)\"\\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format: "Content-Type: application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(imageData!)
body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
request.HTTPBody = body
do
let returnData = try NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)
let returnString = NSString(data: returnData, encoding: NSUTF8StringEncoding)
print("returnString \(returnString)")
catch let error as NSError
print(error.localizedDescription)
task.resume()
我使用此代码,但它不起作用。给我文件位置空。 在这里,我选择图像并存储在数组中,然后从数组上传图像。 我正在使用 .php 网址发送我的图片。
【问题讨论】:
上传图片最好使用Alamofire
这样的第三方库。 github.com/Alamofire/Alamofire
我已经尝试过 Alamofire 但我什么也没得到,因为在每个解决方案中我都需要使用我没有的 API 密钥。我只有在那里上传图片的 URL。是否可以仅使用 URL 在 Alamofire 的服务器上上传图像??? @KrishnaChaitanyaAmjuri
有可能。请检查我的答案。如果它不起作用,请告诉我
框架问题。没有这样的模块“Alamofire”。尝试许多解决方案但不起作用。你有没有更好的解决方案来解决它?我正在使用 Xcode 7.2。@KrishnaChaitanyaAmjuri
您是使用 CocoaPods 添加 Alamofire 还是尝试直接添加?
【参考方案1】:
您可以使用 Alamofire 仅使用 URL 将图像上传到服务器
let imageData = UIPNGRepresentation(image)!
Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON response in
debugPrint(response)
随时提出修改建议以使其变得更好。
【讨论】:
有一个错误 >> 无法使用类型为“(data:NSData, to: String)”的参数列表调用“上传”。【参考方案2】:import MobileCoreServices
func createRequest(userid: String, image: [UIImage]) throws -> NSMutableURLRequest
var parameters: [String : AnyObject] = [
"userid": userid,
"Image1": image[0], // You need to set the UIImage Type image parameters
"Image2": image[1],
"Image3": image[2],
"Image4": image[3]
]
print(parameters)
let boundary = generateBoundaryString()
let url = URL(string: Your URL String)!
let request = NSMutableURLRequest(url: url)
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.httpBody = try createBody(with: parameters as [String : AnyObject], boundary: boundary)
return request
这里是multipart/form-data中上传图片和参数的代码
func createBody(with parameters: [String: AnyObject], boundary: String) throws -> Data
var body = Data()
for (key, value) in parameters
if(value is String || value is NSString)
body.append("--\(boundary)\r\n")
body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.append("\(value)\r\n")
else if(value is UIImage)
let r = arc4random()
let filename = "image\(r).jpg"
let data = UIImageJPEGRepresentation(value as! UIImage,1);
let mimetype = mimeTypeForPath(path: filename)
body.append("--\(boundary)\r\n")
body.append("Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(filename)\"\r\n")
body.append("Content-Type: \(mimetype)\r\n\r\n")
body.append(data!)
body.append("\r\n")
body.append("--\(boundary)--\r\n")
return body
func mimeTypeForPath(path: String) -> String
let pathExtension = path.pathExtension
var stringMimeType = "application/octet-stream";
if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as! CFString, nil)?.takeRetainedValue()
if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue()
stringMimeType = mimetype as NSString as String
return stringMimeType;
extension String
var ns: NSString
return self as NSString
var pathExtension: String?
return ns.pathExtension
var lastPathComponent: String?
return ns.lastPathComponent
【讨论】:
以上是关于如何使用 Swift 将多张图片上传到服务器?的主要内容,如果未能解决你的问题,请参考以下文章
在这种情况下如何将多张图片上传到远程服务器?循环或重复上传过程?