简体   繁体   English

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

[英]how to upload image to server from ios with Alamofire

So i followed this suggestion: https://stackoverflow.com/a/27014372/4751488 . 所以我遵循了这个建议: https : //stackoverflow.com/a/27014372/4751488

When i run my script the photo wont upload. 当我运行脚本时,照片不会上传。 I get no error on the JSON response only that the image has not been uploaded. 我没有收到关于JSON响应的错误,只是图像尚未上传。 Anny ideas? 有想法吗?

my main function: 我的主要功能:

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

and my urlRequestWithComponents looks like this : 和我的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 code : 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 );  

?>

rsponse in xcode: xcode中的rsponse:

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

Old topic but if you're looking for an answer, you use the function move_uploaded_file with the var $target_file which is not initialized. 是旧主题,但是如果要寻找答案,可以将函数move_uploaded_file与未初始化的var $ target_file一起使用。 You should have used $uploadfile 您应该使用$ uploadfile

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM