我想使用 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']);
}
?>
最佳答案
试试这个:
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 循环,它处理多个上传的图像,而不是仅处理一个。
关于php - 使用 AFNetworking 快速上传多个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33672377/