繁体   English   中英

将文件内容从php curl(使用post)发送到C#WebAPI

[英]Sending file contents from php curl (using post) to c# webapi

我必须将文件对象从php传输到c#webapi。 不知何故,在C#中,文件内容以Null的形式出现。 这是除去其他内容后的部分PHP代码

 <?php
 $fileContents =  file_get_contents($_FILES['fileToUpload']['tmp_name']); 

    $uploadFile = new UploadFile();  //custom object
    $uploadFile->fileName = "test";  //string
    $uploadFile->fileContent = $fileContents; //string


    $data_string=json_encode($uploadFile);

    $url="http://localhost:62672/api/uploadfile";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch,CURLOPT_VERBOSE, TRUE);
    //curl_setopt($ch, CURLOPT_PORT, 801);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");

    curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);

    curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',

    ));

?>

这是C#控制器代码和模型代码

 public class CrmUploadFileModel
    {
        public string fileName { get; set; }
        public byte[] fileContent { get; set; }


    }
public class UploadFileController : BaseController
    {

        public IHttpActionResult Post([FromBody]CrmUploadFileModel value)
        {
// here .. i find that the value.fileContent is null. 
}

刚开始学习.NET,因此不知道.NET代码是否有问题。

使用相同的PHP代码,我能够将文件内容成功发送到.NET Web服务,这是一个单独的应用程序。

提前致谢。 祖阿曼

从您的代码确认中,我看到发布的fileContent是一个string ,并且您正尝试将其作为byte[]接收。 您应该将CrmUploadFileModel.fileContent的类型CrmUploadFileModel.fileContentstring ,它应该可以正常工作。 请参阅下面的注释

由于您没有显示路由配置,因此我不知道发布操作中是否缺少[HttpPost]属性是否是另一个问题。 如果将其添加到代码中,则不会造成任何危害,并且我们可以放弃此问题(实际上,如果您的调试器输入了Post操作,那么这不是问题)。

注意 :如果要发布和接收字节数组,则不能直接在JSON对象中进行操作,除非您在客户端将其编码为字符串并在服务器中对其进行解码。 如果仍要发送字节数组,则不能期望自动进行参数绑定,而必须做额外的工作: 如何从C#中的Web Api方法正确获取字节数组? 正如您在该问答中所看到的,您必须将整个发布的值转换为byte[] ,因此发送多个属性甚至更加困难(您必须手动解析该数组)。

暂无
暂无

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

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