如何使用Alamofire从ios上传图像到服务器

时间:2015-06-16 10:21:08

标签: php ios alamofire

所以我遵循了这个建议:https://stackoverflow.com/a/27014372/4751488

当我运行我的脚本时,照片不会上传。仅在图像尚未上传时,我没有收到JSON响应的错误。安妮的想法?

我的主要职能:

var image : UIImage = UIImage(named:"record")!
    let imageData2 = UIImagePNGRepresentation(image)

    imageViewController.image = image

    var parameters = [
        "pic"           :NetData(data: imageData2!, mimeType: MimeType.ImageJpeg ,filename: "customName.jpg"),
        "otherParm"     :"Value"
    ]


    let urlRequest = self.urlRequestWithComponents("http://www.xxx.xx/uploadPhoto.php", parameters: parameters)

    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)")
    }

我的urlRequestWithComponents看起来像这样:

func urlRequestWithComponents(urlString:String, parameters:NSDictionary) -> (URLRequestConvertible, NSData) {

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


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

    // add parameters
    for (key, value) in parameters {

        uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

        if value is NetData {
            // add image
            var postData = value as! NetData


            //uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(postData.filename)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

            // append content disposition
            var filenameClause = " filename=\"\(postData.filename)\""
            let contentDispositionString = "Content-Disposition: form-data; name=\"\(key)\";\(filenameClause)\r\n"
            let contentDispositionData = contentDispositionString.dataUsingEncoding(NSUTF8StringEncoding)
            uploadData.appendData(contentDispositionData!)


            // append content type
            //uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) // mark this.
            let contentTypeString = "Content-Type: \(postData.mimeType.getString())\r\n\r\n"
            let contentTypeData = contentTypeString.dataUsingEncoding(NSUTF8StringEncoding)
            uploadData.appendData(contentTypeData!)
            uploadData.appendData(postData.data)

        }else{
            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)
}

php代码:

<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.

$uploaddir = "/var/www/html/upload/uploads/";

// PS: custom filed name : pic
$uploadfile = $uploaddir . basename($_FILES['pic']['name']);

  if (move_uploaded_file($_FILES["pic"]["tmp_name"], $target_file)) {
   $array = array ("code" => "1", "message" => "successfully");  
} else {
   $array = array ("code" => "0", "message" => "Possible file upload         attack!".$uploadfile); 
}

echo json_encode ( $array );  

?>
xcode中的

rsponse:

JSON Optional({
code = 0;
message = "Possible file upload attack!/var/www/html/upload/uploads/customName.jpg";})
ERROR nil

1 个答案:

答案 0 :(得分:2)

旧主题但是如果您正在寻找答案,则使用函数move_uploaded_file和未初始化的var $ target_file。 你应该使用$ uploadfile