版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Song_Lynn/article/details/79645674
Webapi之文件上传
范例说明:
- 前端:vue.js + element-ui + axios
- 后端:c# webapi
- 先上传存储起来,然后再读取文件
- 仅尝试过在本地调试,未验证服务器
前端部分
- 使用element-ui的上传组件
// html 直接调用api
<el-upload
class="upload-demo"
ref="upload"
:action="/api/handledoc/upload'"
:show-file-list="false"
:multiple="false"
:limit="1">
<el-button size="mini" round icon="el-icon-upload">导入</el-button>
</el-upload>
- 使用原生input
// html
<input id="file" type="file" @change="uploadExcel"/>
// js,调用api
uploadExcel: function () {
var file = document.getElementById('file').files[0];
var formData = new FormData();
formData.append('file', file);
console.log(file);
this.axios({
url: '/api/handledoc//upload',
method: 'post',
cache: false, //上传文件不需要缓存
data: formData,
processData: false, //因为data值是FormData对象,不需要对数据做处理
contentType: false
}).then((res) => {
}, (res) => {
});
},
后端部分
[RoutePrefix("api/handledoc")]
public class HandleDocumentController : ApiController
{
static string fileUrl = @"/document/"; //
// api/handledoc/upload
[Route("upload")]
[HttpPost]
public void uploadDoc()
{
// 上传存储
/*var res = HttpContext.Current.Request;
var file = res.Form["file"][0];*/
HttpPostedFile file = HttpContext.Current.Request.Files[0];
string type = file.ContentType;
string name = DateTime.Now.ToString("yyyyMMddhhmmss") + "_" + file.FileName;
string path = System.Web.Hosting.HostingEnvironment.MapPath(fileUrl + "import/" + name);
file.SaveAs(path);
//存储完成
// 读取文件,读取数据,进行其它操作
FileStream fs = new FileStream(path , FileMode.Open);
... ...
}
}