gpt4 book ai didi

swift - 使用 alamofire 上传图片

转载 作者:IT王子 更新时间:2023-10-29 05:50:01 39 4
gpt4 key购买 nike

我正在尝试使用 Alamofire 将图像上传到服务器,但我的代码不起作用。这是我的代码:

var parameters = ["image": "1.jpg"]
let image = UIImage(named: "1.jpg")
let imageData = UIImagePNGRepresentation(image)
let urlRequest = urlRequestWithComponents("http://tranthanhphongcntt.esy.es/task_manager/IOSFileUpload/", parameters: parameters, imageData: imageData)
Alamofire.upload(urlRequest.0, data: urlRequest.1)
.progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
println("\(totalBytesWritten) / \(totalBytesExpectedToWrite)")
}
.responseJSON { (request, response, JSON, error) in
println("REQUEST \(request)")
println("RESPONSE \(response)")
println("JSON \(JSON)")
println("ERROR \(error)")
}

这是 urlRequestWithComponents 方法:

func urlRequestWithComponents(urlString:String, parameters:Dictionary<String, String>, imageData:NSData) -> (URLRequestConvertible, NSData) {

// create url request to send
var mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!)
mutableURLRequest.HTTPMethod = Alamofire.Method.POST.rawValue
let boundaryConstant = "myRandomBoundary12345";
let contentType = "multipart/form-data;boundary="+boundaryConstant
mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")



// create upload data to send
let uploadData = NSMutableData()

// add image
uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData("Content-Disposition: form-data; name=\"file\"; filename=\"file.png\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData(imageData)

// add parameters
for (key, value) in parameters {
uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)
}
uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)



// return URLRequestConvertible and NSData
return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData)
}

这是我在控制台中得到的:

REQUEST { URL: http://tranthanhphongcntt.esy.es/task_manager/IOSFileUpload/ } RESPONSE Optional( { URL: http://tranthanhphongcntt.esy.es/task_manager/IOSFileUpload/ } { status code: 200, headers { "Accept-Ranges" = bytes; Connection = close; "Content-Length" = 345; "Content-Type" = "text/html"; Date = "Tue, 25 Aug 2015 10:52:01 GMT"; "Last-Modified" = "Mon, 24 Aug 2015 03:54:55 GMT"; Server = Apache; } }) JSON nil ERROR Optional(Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x7f8c68c1c130 {NSDebugDescription=Invalid value around character 0.})

我的 PHP 内容:

<? php
echo $_FILES['image']['name'].
'<br/>';


//ini_set('upload_max_filesize', '10M');
//ini_set('post_max_size', '10M');
//ini_set('max_input_time', 300);
//ini_set('max_execution_time', 300);


$target_path = "uploads/";

$target_path = $target_path.basename($_FILES['image']['name']);

try {
//throw exception if can't move the file
if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
throw new Exception('Could not move file');
}

echo "The file ".basename($_FILES['image']['name']).
" has been uploaded";
} catch (Exception $e) {
die('File did not upload: '.$e - > getMessage());
} ?>

我的代码遵循了这个建议:Uploading file with parameters using Alamofire.请帮助我,谢谢

最佳答案

同时 Rob's答案正确,这里是 Swift 2.0 版本,有上传进度更新。

只需复制并粘贴以下代码,更改上传 URL,并添加您的参数。应该像魅力一样工作。

附言:MRProgress是一个很棒的进度更新库!

    let apiToken = "ABCDE"
Alamofire.upload(
.POST,
"http://sample.com/api/upload",
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: imageData, name: "yourParamName", fileName: "imageFileName.jpg", mimeType: "image/jpeg")
multipartFormData.appendBodyPart(data: apiToken.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"api_token")
multipartFormData.appendBodyPart(data: otherBodyParamValue.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"otherBodyParamName")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
print("Uploading Avatar \(totalBytesWritten) / \(totalBytesExpectedToWrite)")
dispatch_async(dispatch_get_main_queue(),{
/**
* Update UI Thread about the progress
*/
})
}
upload.responseJSON { (JSON) in
dispatch_async(dispatch_get_main_queue(),{
//Show Alert in UI
print("Avatar uploaded");
})
}

case .Failure(let encodingError):
//Show Alert in UI
print("Avatar uploaded");
}
}
);

关于swift - 使用 alamofire 上传图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32202547/

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