我正试图使用阿拉莫菲尔上传文件。使用文件(NSUrl
)时,上传效果很好,但是,我似乎不知道如何使用NSData
选项?
这是我的测试:
var url:NSURL = NSURL.URLWithString("http://localhost:8080/bike.jpeg")
var err: NSError?
var imageData :NSData = NSData.dataWithContentsOfURL(url,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
Alamofire.upload(.POST, "http://localhost:8080/rest/service/upload/test.png", imageData)
.progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
println(totalBytesWritten)
}
.responseJSON { (request, response, JSON, error) in
println(request)
println(response)
println(JSON)
}
我的状态代码是415?
此外,如何在上传中发送其他参数?
谢啦
编辑
我没有设置正确的内容类型:
var manager = Manager.sharedInstance
manager.session.configuration.HTTPAdditionalHeaders = ["Content-Type": "application/octet-stream"]
let imageData: NSMutableData = NSMutableData.dataWithData(UIImageJPEGRepresentation(imageTest.image, 30));
Alamofire.upload(.POST, "http://localhost:8080/rest/service/upload?attachmentName=file.jpg", imageData)
.progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
println(totalBytesWritten)
}
.responseString { (request, response, JSON, error) in
println(request)
println(response)
println(JSON)
}
仍然不知道如何发送附加参数随上传。
以下是基于antiblanks答案的使用Alamofire 3.0的解决方案:
let parameters = [
"par1": "value",
"par2": "value2"]
let URL = "YOUR_URL.php"
let image = UIImage(named: "image.png")
Alamofire.upload(.POST, URL, multipartFormData: {
multipartFormData in
if let _image = image {
if let imageData = UIImageJPEGRepresentation(_image, 0.5) {
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "file.png", mimeType: "image/png")
}
}
for (key, value) in parameters {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
}, encodingCompletion: {
encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseObject { (response: Response<UploadData, NSError>) -> Void in
switch response.result {
case .Success:
completionHandler?(success: true)
case .Failure(let error):
completionHandler?(success: false)
}
}
case .Failure(let encodingError):
print(encodingError)
}
})
通过Swift 3上传带有参数和自定义标题的照片/文件
// import Alamofire
func uploadWithAlamofire() {
let image = UIImage(named: "bodrum")!
// define parameters
let parameters = [
"hometown": "yalikavak",
"living": "istanbul"
]
Alamofire.upload(multipartFormData: { multipartFormData in
if let imageData = UIImageJPEGRepresentation(image, 1) {
multipartFormData.append(imageData, withName: "file", fileName: "file.png", mimeType: "image/png")
}
for (key, value) in parameters {
multipartFormData.append((value?.data(using: .utf8))!, withName: key)
}}, to: "upload_url", method: .post, headers: ["Authorization": "auth_token"],
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { [weak self] response in
guard let strongSelf = self else {
return
}
debugPrint(response)
}
case .failure(let encodingError):
print("error:\(encodingError)")
}
})
}
通过Swift 2和Alamofire 3
// import Alamofire
func uploadWithAlamofire() {
let image = UIImage(named: "myImage")!
// define parameters
let parameters = [
"hometown": "yalikavak",
"living": "istanbul"
]
// Begin upload
Alamofire.upload(.POST, "upload_url",
// define your headers here
headers: ["Authorization": "auth_token"],
multipartFormData: { multipartFormData in
// import image to request
if let imageData = UIImageJPEGRepresentation(image, 1) {
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "myImage.png", mimeType: "image/png")
}
// import parameters
for (key, value) in parameters {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
}, // you can customise Threshold if you wish. This is the alamofire's default value
encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold,
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .Failure(let encodingError):
print(encodingError)
}
})
}
当前swift版本:https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#uploading-数据到服务器
下面是一个简单的函数,它需要目标上载url、参数和imageData,并返回Alamofire.upload上载带有参数的图像所需的UrlRequestConverable和NSData。
// this function creates the required URLRequestConvertible and NSData we need to use Alamofire.upload
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)
}
下面是一个如何使用它的示例(请参阅创建和发送请求):
// init paramters Dictionary
var parameters = [
"task": "task",
"variable1": "var"
]
// add addtionial parameters
parameters["userId"] = "27"
parameters["body"] = "This is the body text."
// example image data
let image = UIImage(named: "177143.jpg")
let imageData = UIImagePNGRepresentation(image)
// CREATE AND SEND REQUEST ----------
let urlRequest = urlRequestWithComponents("http://example.com/uploadText/", parameters: parameters, imageData: imageData)
Alamofire.upload(urlRequest.0, 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)")
}
如果您需要目标url的php文件(同一目录中有一个“uploads”文件夹):
// get picture variables
$file = $_FILES['file']['tmp_name'];
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
// check extension
$allowedExts = array("jpg", "jpeg", "png");
$rootName = reset(explode(".", $fileName));
$extension = end(explode(".", $fileName));
// create new file name
$time = time();
$newName = $rootName.$time.'.'.$extension;
// temporarily save file
$moved = move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/".$newName );
if ($moved) $path = "uploads/".$newName;
$body = $_POST['body'];
$userId = $_POST['userId'];
$time = time();
if ($moved) {
$fullUrl = "http://antiblank.com/testPhotoUpload/".$path;
$arrayToSend = array('status'=>'success','time'=>$time,'body'=>$body,'userId'=>$userId, "imageURL"=>$fullUrl);
} else {
$arrayToSend = array('status'=>'FAILED','time'=>$time,'body'=>$body,'userId'=>$userId);
}
header('Content-Type:application/json');
echo json_encode($arrayToSend);
我试图使用AlamoFire将图像(avatarImage)作为formData参数类型上载到服务器,但每次我尝试发布时都会生成一个“数据无法读取,因为它的格式不正确”错误。我不太清楚我做错了什么。 PS:我正在使用multipartFormData上载b/c,我还需要发送一些其他参数(一旦我能够上载图像)。
我正在使用Alamofire向服务器发送数据。我有一个图像,我想上传到服务器的数据形式与一些其他参数。在Alamofire中,我使用multipartFormData方法发布所有参数和图像。服务器需要数据为JSON格式,参数如下所示: 我正在努力,但它给了我一个失败的回应。以下是我在swift中与alamofire合作的代码: 我的服务器接受BLOB数据中的映像。如果有人能帮我。非常感谢。
我正在执行以下操作以上载带有参数的PNG文件: 问题是,在我的服务器上,我看不到和表单字段。我遵循了网上发布的例子。有什么我应该做的不同吗? 编辑 如果我移除我放置的零件: 然后包括参数。否则,我认为这是Alamofire 4.0.1中的一个错误。
我正在用Swift开发一个iPhone应用程序。我正在使用Alamofire框架来处理http请求。我将用于POST,GET等,如下所示: 我使用将图像上载到服务器: 谁能帮我解决这个问题? 谢谢!:)
我想使用cURL不仅以HTTP POST发送数据参数,而且还上传具有特定表单名称的文件。我该怎么做呢?
我正试图用Alamofire将图像上传到服务器,但我的代码不起作用。这是我的代码: 这是urlRequestWithComponents方法: 这就是我在控制台得到的: 请求{URL:http://tranthanhphongcntt.esy.es/task_manager/IOSFileUpload/ }响应可选({URL:http://tranthanhphongcntt.esy.es/tas