当前位置 主页 > 网站技术 > 代码类 > 最大化 缩小

    asp.net大文件上传解决方案实例代码

    栏目:代码类 时间:2019-09-11 18:14

    以ASP.NET Core WebAPI 作后端 API ,用 Vue 构建前端页面,用 Axios 从前端访问后端 API ,包括文件的上传和下载。

    准备文件上传的API

    #region 文件上传 可以带参数  [HttpPost("upload")]  public JsonResult uploadProject(IFormFile file, string userId)  {   if (file != null)   {    var fileDir = "D:\\aaa";    if (!Directory.Exists(fileDir))    {     Directory.CreateDirectory(fileDir);    }    //文件名称    string projectFileName = file.FileName;     //上传的文件的路径    string filePath = fileDir + $@"\{projectFileName}";    using (FileStream fs = System.IO.File.Create(filePath))    {     file.CopyTo(fs);     fs.Flush();    }    return Json("ok");   }else{    return Json("no");   }  }  #endregion

    前端vue上传组件 ( 利用Form表单上传 )

    <template><div> <form>  <input type="text" value="" v-model="projectName" placeholder="请输入项目名称">  <input type="file" v-on:change="getFile($event)">  <button v-on:click="submitForm($event)">上传</button> </form></div></template> <script>///这个组件是用于上传bdls文件的组件export default { data() { return {  uploadURL: "/Home/Upload",  projectName: "",  file: "" }; }, methods: { getFile(event) {  this.file = event.target.files[0];  console.log(this.file); }, submitForm(event) {  event.preventDefault();  let formData = new FormData();  formData.append("file", this.file);   let config = {  headers: {   "Content-Type": "multipart/form-data"  }  };   this.$http  .post(this.uploadURL, formData, config)  .then(function(response) {   if (response.status === 200) {   console.log(response.data);   }  }); } }};</script> <style lang="scss" scoped></style>

    用 element-ui 的 Upload组件上传文件

    http://element-cn.eleme.io/#/zh-CN/component/upload

    <template><div> <el-upload  class="upload-css"  :file-list="uploadFiles"  ref="upload"  :on-success="upLoadSuccess"  :on-error="upLoadError"  :action="uploadURL"  :auto-upload="false">  <el-button slot="trigger" size="small" type="primary">选取文件</el-button>  <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> </el-upload></div></template> <script>import Vue from "vue";import { Upload, Button } from "element-ui";Vue.use(Upload);Vue.use(Button); export default { props: [], data() { return {  projectName: "",  //uploadURL: "/project/upload?a=1",  uploadFiles: [] //上传的文件列表 }; }, computed: { //文件的上传路径 //附带用户id和项目名称 uploadURL: function() {  //var userId = this.$store.state.userId;  return "/project/upload?userId=" + 1; } }, methods: { //文件上传 submitUpload() {  this.$refs.upload.submit(); }, //文件上传成功时的钩子 upLoadSuccess(response, file, fileList) {  if (response == "ok") {  console.log(response + "已上传" + file);  console.log("项目添加成功");  } else {  console.log("项目添加失败");  } }, //文件上传失败时的钩子 upLoadError(response, file, fileList) {  console.log("项目添加失败"); } }};</script> <style lang="scss" scoped></style>
    
    下一篇:没有了