使用 AFNetworking 快速上传多张图片
Posted
技术标签:
【中文标题】使用 AFNetworking 快速上传多张图片【英文标题】:Upload multiple images using AFNetworking in swift 【发布时间】:2015-11-12 13:19:49 【问题描述】:我想在 swift 中使用AFNetworking
将多张图片上传到我的网站,但只上传了array
中的最后一张图片。
swift 脚本:
let url = "http://pathtomysite"
let afHTTP : AFHTTPRequestSerializer = AFHTTPRequestSerializer()
let request: NSMutableURLRequest = afHTTP.multipartFormRequestWithMethod("POST", URLString: url, parameters: nil, constructingBodyWithBlock: (formData: AFMultipartFormData) in
var i = 0
for image in upImage
let imageData : NSData = UIImageJPEGRepresentation(image as UIImage, 0.5)!
formData.appendPartWithFileData(imageData, name: "uploaded_file", fileName: "imagex\(i)x.png", mimeType: "image/png")
i++
, error: nil)
let managerS : AFURLSessionManager = AFURLSessionManager.init(sessionConfiguration: NSURLSessionConfiguration.defaultSessionConfiguration())
let uploadTask = managerS.uploadTaskWithStreamedRequest(request, progress: nil) (response, AnyObject, error) -> Void in
if (error != nil)
print("error")
uploadTask.resume()
php 脚本:
<?php
$dt = date("Ymdhis");
$fileInfo = pathinfo($_FILES['uploaded_file']['name']);
$file_path = "uploads/";
$file_path = $file_path . basename($_FILES['uploaded_file']['name']);
if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path))
rename($file_path, 'uploads/' . $dt . '.' . $fileInfo['extension']);
?>
【问题讨论】:
【参考方案1】:试试这个:
let url = "YOUR_URL"
let afHTTP : AFHTTPRequestSerializer = AFHTTPRequestSerializer()
let request: NSMutableURLRequest = afHTTP.multipartFormRequestWithMethod("POST", URLString: url, parameters: nil, constructingBodyWithBlock: (formData: AFMultipartFormData) in
for (index, image) in upImage.enumerate()
let imageData = UIImageJPEGRepresentation(image as UIImage, 0.5)!
formData.appendPartWithFileData(imageData, name: "uploaded_file[]", fileName: "imagex\(index)x.png", mimeType: "image/png")
, error: nil)
let managerS : AFURLSessionManager = AFURLSessionManager.init(sessionConfiguration: NSURLSessionConfiguration.defaultSessionConfiguration())
let uploadTask = managerS.uploadTaskWithStreamedRequest(request, progress: nil) (response, AnyObject, error) -> Void in
if (error != nil)
print("error")
uploadTask.resume()
并将您的脚本更改为以下内容:
foreach ($_FILES["uploaded_file"]["tmp_name"] as $index => $tmp_name)
$filePath = "uploads/" . basename($_FILES["uploaded_file"]["name"][$index]);
if (move_uploaded_file($tmp_name, $filePath))
// rename like you want to
重要的是在上传代码中的 uploaded_file[] 中添加括号。如果您不包含 [],则每张图片上传都会覆盖最后一张。
另一个重要的部分是脚本中的 foreach 循环,它处理多个上传的图像,而不仅仅是一个。
【讨论】:
以上是关于使用 AFNetworking 快速上传多张图片的主要内容,如果未能解决你的问题,请参考以下文章
ios 上传多张图片总结——IOS网络访问之使用AFNetworking
ios 上传多张图片总结——IOS网络访问之使用AFNetworking
关于最新版AFNetworking(3.0)上传多张图片的问题