简体   繁体   中英

Upload File using cURL to asp.net mvc action

I am trying to upload a file from PHP using cURL to a asp.net mvc 4 controller action. The file is successfully uploaded on disk after move_uploaded_file is called.

Both .NET MVC and PHP sites are hosted under IIS. I get this HTTP Response:

Bad Request - Invalid Content Length

Has anyone achieved this?

Relevant PHP code:

    if(move_uploaded_file($from, $to))
    {       
        $imageFile = '@' . $to . ';type='.$_FILES['file']['type'];

        $post_data = http_build_query($_POST);
        $post_data["imageFile"] = $imageFile;

        $ch = curl_init(self::URL . '/photos/uploadphoto');                                                                      
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    
        curl_setopt($ch, CURLOPT_POST, 1);                                                                      
        curl_setopt($chpg, CURLOPT_POST, count($data));
        curl_setopt($chpg, CURLOPT_POSTFIELDS, $data);                                                                                
        $result = curl_exec($ch);
        curl_close($ch); 
    }

Relevant .NET C# code:

   [HttpPost]
    public ActionResult UploadPhoto(HttpPostedFileBase imagefile)
    {
        //  imageFile is null
            var file = Request.Files.Count > 0 ? Request.Files[0] : null;
        // file is also null
        ...
     }

Are you sure about $chpg? i believe this is where are going wrong, perhaps you need to change $chpg to $ch, try using the following 2 lines of code:

curl_setopt($ch, CURLOPT_POST, count($data));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

Instead of:

curl_setopt($chpg, CURLOPT_POST, count($data));
curl_setopt($chpg, CURLOPT_POSTFIELDS, $data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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