Subir imagen con alamofire
Estoy tratando de subir una imagen al servidor con Alamofire pero mi código no funciona. Este es mi código:
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)")
}
y este es urlRequestWithComponents methos:
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)
}
y esto es lo que obtengo en la consola:
SOLICITAR {URL:http://tranthanhphongcntt.esy.es/task_manager/IOSFileUpload/ } RESPUESTA Opcional ({URL:http://tranthanhphongcntt.esy.es/task_manager/IOSFileUpload/ } {código de estado: 200, encabezados {"Aceptar-Rangos" = bytes; Conexión = cerrar; "Longitud del contenido" = 345; "Content-Type" = "text / html"; Fecha = "Martes, 25 de agosto de 2015 10:52:01 GMT"; "Last-Modified" = "Lun, 24 ago 2015 03:54:55 GMT"; Servidor = Apache; }}) JSON nil ERROR Opcional (Error Domain = NSCocoaErrorDomain Code = 3840 "La operación no se pudo completar. (Error de Cocoa 3840.)" (Valor no válido alrededor del carácter 0.) UserInfo = 0x7f8c68c1c130 {NSDebugDescription = Valor no válido alrededor del carácter 0 .})
mi contenido 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());
} ?>
Mi código siguió esta sugerencia:Subir archivo con parámetros usando Alamofire Por favor, ayúdame, gracias