码迷,mamicode.com
首页 > Web开发 > 详细

CSharp Web实现文件上传下载功能实例解析

时间:2020-05-12 16:42:52      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:获取文件   computed   对象   发送请求   v-model   OLE   请求   mime   地址栏   

以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>

文件下载

普通的文件下载方式是访问一个后台文件流地址,直接生成对应的文件,下载即可,地址栏中也可携带一些控制参数,但是无法通过header传递参数。

 

两种文件下载方式,一种是,直接返回file文件,利用浏览器的下载功能。但是这种没有发现可以在发送请求的时候携带token;另一种是利用 Axios 发送下载文件的请求,可以设置header头,可以携带token ,但是response-type是blob类型的。

 

第一种:

后端API:

 

public FileResult downloadRequest()

        {

            //var addrUrl = webRootPath + "/upload/thumb.jpg";

            var addrUrl = "D:/aaa/thumb.jpg";

 

            var stream = System.IO.File.OpenRead(addrUrl);

 

            string fileExt = Path.GetExtension("thumb.jpg");

 

            //获取文件的ContentType

 

            var provider = new FileExtensionContentTypeProvider();

 

            var memi = provider.Mappings[fileExt];

 

            return File(stream, memi, Path.GetFileName(addrUrl));

        }

前端利用浏览器的功能url直接返回文件

 

下载文件...

...

...

 

downloadRequest() {   

    let url = "Home/downloadRequest"; //可以在路径中传递参数

    window.location.href = url;

 },

第二种

后端api ,两个api的返回类型不同,asp.net core 文件下载常用的有FileResult 、FileContentResult 、 FileStreamResult。

 

public FileContentResult downloadRequest1()

        {

            //string webRootPath = _hostingEnvironment.WebRootPath;

            //var addrUrl = webRootPath + "/upload/thumb.jpg";

            var addrUrl = "D:/aaa/wyy.exe";

 

            /*var stream = System.IO.File.OpenRead(addrUrl);

 

            string fileExt = Path.GetExtension("thumb.jpg");

 

            //获取文件的ContentType

 

            var provider = new FileExtensionContentTypeProvider();

 

            var memi = provider.Mappings[fileExt];

 

            return File(stream, memi, Path.GetFileName(addrUrl));*/

 

            //return stream;

            byte[] fileBytes = System.IO.File.ReadAllBytes(addrUrl);

            string fileName = "wyy.exe";

            return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); //关键语句

        }

前端页面

 

blob(用来存储二进制大文件)

 

<el-button type="primary" v-on:click="downloadRequest1">下载文件11</el-button>

...

...

...

    downloadRequest1() {

      axios({

        // 用axios发送post请求

        method: "post",

        url: "Home/downloadRequest1", // 请求地址 ,也可以传递参数

        headers: {

          //可以自定义header

          gggg: "gggggggggggggggggggggggggggggggggggggggggggggggggggg"  //可以携带token

        },

        responseType: "blob" // 表明返回服务器返回的数据类型

      }).then(res => {

        // 处理返回的文件流

        //主要是将返回的data数据通过blob保存成文件

        var content = res.data;

        var blob = new Blob([content]);

        var fileName = "wyy.exe"; //要保存的文件名称

        if ("download" in document.createElement("a")) {

          // 非IE下载

          var elink = document.createElement("a");

          elink.download = fileName;

          elink.style.display = "none";

          elink.href = URL.createObjectURL(blob);

          document.body.appendChild(elink);

          elink.click();

          URL.revokeObjectURL(elink.href); // 释放URL 对象

          document.body.removeChild(elink);

        } else {

          // IE10+下载

          navigator.msSaveBlob(blob, fileName);

        }

        console.log(res);

      });

    }

第三种

就是用用up6控件,此控件支持mac、windos、Linux,因为太长就不发了,详细可以参考这篇文章:http://blog.ncmem.com/wordpress/2019/08/09/asp-net%e6%96%87%e4%bb%b6%e4%b8%8a%e4%bc%a0%e4%b8%8b%e8%bd%bd/

欢迎入群一起讨论:374992201

CSharp Web实现文件上传下载功能实例解析

标签:获取文件   computed   对象   发送请求   v-model   OLE   请求   mime   地址栏   

原文地址:https://www.cnblogs.com/songsu/p/12876850.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!