当前位置: 移动技术网 > IT编程>开发语言>.net > .Net Core2.2 WebApi上传文件

.Net Core2.2 WebApi上传文件

2019年07月26日  | 移动技术网IT编程  | 我要评论

双生公主奇遇记,win7锐捷客户端下载,七滴眼泪 姜玉阳

基于.net core2.2的webapi程序,接收客户端上传的文件.按照以下写法,file的值永远是null

[httppost]
public void post([fromform] iformfile file)
{

}

一.有两种方法解决这个问题:

1.属性绑定.在[fromform]里添加name属性如:[fromform(name = "file")],客户端调用时需要保持一致

// post api/values
[httppost] public void post([fromform(name = "file")] iformfile file) { }

还可以和其他参数一起传过来

 // post api/<controller>
        [httppost]
        public async task<iactionresult> uploadfile(string filename,[fromform(name ="file")]iformfile formfile)

 

postman测试,注意参数名要保持一致,否则收到的值为null

 

2.通过request.form.files获取文件,客户端可以任意指定name

 // post api/values
[httppost] public void post() { iformfile formfile= request.form.files[0]; var filepath = @"d:\uploadingfiles\" + formfile.filename; if (formfile.length > 0) { using (var stream = new filestream(filepath, filemode.create)) { formfile.copyto(stream); } } }

 二.客户端调用代码

  var request = new restrequest(method.post);
            request.addfile("file", @"d:\1.jpg");
            var restclient = new restclient("http://localhost:63270/api/values");
            irestresponse response = restclient.execute(request);

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网