C# 實現上傳和下載文件(Vue+axios+Element UI)

前端:Vue+axios+Element UI

后端:C# .Net 一般處理程序(ashx)


上傳文件

前端代碼 Element UI

使用Element UI的el-upload組件

<!-- action:文件上傳的URL地址(必需)../../../../../ISV/AttachmentSite/FileUpload.ashx -->
<!-- drag:是否啟用拖拽上傳 -->
<!-- multiple:是否支持多選文件 -->
<!-- limit:最大允許上傳個數 -->
<!-- file-list:上傳的文件列表 -->
<!-- http-request:自定義上傳行為:http-request="FileUploadRequest"-->
<!-- on-success:文件上傳成功時的鉤子 -->
<!-- on-error:文件上傳失敗時的鉤子-->
<!-- before-upload:文件上傳之前的鉤子,返回false終止上傳-->
<!-- on-change:文件狀態改變時的鉤子,添加文件、上傳成功和上傳失敗時都會被調用-->
<el-upload style="width:100%"
            class="upload-demo"
            :action="actionUrl"
            :file-list="fileList"
            :on-success="FileOnSuccess"
            :on-error="FileOnError"
            :before-upload="FileBeforeUpload"
            :on-change="FileOnChange"
            :limit="11"
            multiple
            drag>
    <i class="el-icon-upload"></i>
    <div class="el-upload__text">將文件拖到此處,或<em>點擊上傳</em></div>
    <div class="el-upload__tip" slot="tip">上傳文件不能超過100M</div>
</el-upload>
后端代碼 C# (ashx)
public class FileUpload : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json";
        try
        {
            string userID = HttpContext.Current.Request.QueryString["userID"];

            //HttpPostedFile Files=context.Request.Files["File"];// 單個文件
            HttpFileCollection Files = HttpContext.Current.Request.Files;// 多個文件

            string AbsolutePath = ConfigurationManager.AppSettings["IsAbsolutePath"];
            bool IsAbsolutePath = Convert.ToBoolean(AbsolutePath);// 是否啟用絕對路徑

            string FilePath = "";// 文件路徑
            if (IsAbsolutePath)
            {
                FilePath = ConfigurationManager.AppSettings["FilePath"].ToString();// 絕對文件路徑
            }
            else
            {
                FilePath = HttpContext.Current.Request.PhysicalApplicationPath+ "\\Attachment\\";// 獲取應用程序的根路徑
                //FilePath = FilePath.Replace("AttachmentSite", "Attachment");// 將站點地址替換為文件地址
            }

            // 判斷文件路徑是否存在
            if (!System.IO.Directory.Exists(FilePath))
            {
                System.IO.Directory.CreateDirectory(FilePath);//創建文件夾
            }

            // 保存文件
            Dictionary<string, string> dicFilePath = new Dictionary<string, string>();// 返回結果字典
            foreach (string strFile in Files)
            {
                HttpPostedFile File = Files[strFile];// 用key獲取單個文件對象HttpPostedFile
                File.SaveAs(FilePath + File.FileName);// 保存文件
                dicFilePath.Add(File.FileName, FilePath + File.FileName);
            }

            LogHelper.AppDebugLog("[FileUpload] userID=" + userID + " 文件路徑:" + JsonConvert.SerializeObject(new { FilePath = dicFilePath }));
            context.Response.Write(JsonConvert.SerializeObject(new { FilePath = dicFilePath }));
        }
        catch (Exception e)
        {
            LogHelper.AppErrorLog(e, "[FileUpload] " + e.Message);
            context.Response.Write(JsonConvert.SerializeObject(new { Error = e.Message }));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Web.config文件中配置了跨域、上傳文件限制大小、上傳文件路徑的配置項

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2"/>
    <httpRuntime targetFramework="4.5.2" maxRequestLength="1048576000" executionTimeout="3600"/>
  </system.web>

<!--跨域請求-->
<system.webServer>
  <httpProtocol>
    <customHeaders>
      <!--允許的請求方式-->
      <add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/>
      <!--允許的請求頭信息-->
      <add name="Access-Control-Allow-Headers" value="x-requested-with,content-type"/>
      <!--允許的請求地址 *表示所有-->
      <add name="Access-Control-Allow-Origin" value="*"/>
      <!--是否攜帶cookie信息,注意:為true時,Access-Control-Allow-Origin不允許為*-->
      <add name="Access-Control-Allow-Credentials" value="false"/>
    </customHeaders>
  </httpProtocol>
  
  <security>
    <requestFiltering>
      <!--文件大小限制 1000 MB  -->
      <requestLimits maxAllowedContentLength="1048576000" />
    </requestFiltering>
  </security>
</system.webServer>

  <appSettings>
    <!--是否啟用絕對路徑-->
    <add key="IsAbsolutePath" value="false" />
    <!--絕對文件路徑-->
    <add key="FilePath" value="C:\Attachment\" />
  </appSettings>

</configuration>

下載文件(單個文件)

前端代碼 Vue+axios

按鈕調用methods中的FileDownloadRequest方法
就打算離開房間 jdsk 十九點.zip 是文件名稱(有中文有空格)

// 下載文件
FileDownloadRequest: function () {
    // 發起Ajax請求
    axios({
        method: 'post',
        url: 'http://localhost:8022/FileDownload.ashx',// 服務器CRM附件站點
        responseType: 'blob'
    })
        // 下載文件成功
        .then(res => {
            console.log(res);
            //對于<a>標簽,只有 Firefox 和 Chrome(內核) 支持 download 屬性,IE10+支持blob但是依然不支持download
            if ('download' in document.createElement('a')) {//支持a標簽download的瀏覽器
                let url = window.URL.createObjectURL(res.data);//為文件流創建構建下載鏈接
                let link = document.createElement('a');//創建a標簽
                link.style.display = 'none';
                link.href = url;
                link.setAttribute('download', "就打算離開房間 jdsk 十九點.zip");//設置a標簽的下載動作和下載文件名 /row.new_filefullname
                document.body.appendChild(link);
                link.click();//執行下載
                document.body.removeChild(link);//釋放標簽
            }
            else {
                //其他瀏覽器
                navigator.msSaveBlob(res.data, "就打算離開房間 jdsk 十九點.zip");
            }
        })
        // 下載文件失敗
        .catch(err => {
            console.log(err);
            this.$message.error({ message: err.message });
        })
},

后端代碼 C# (ashx)

C# TransmitFile 方式下載
特別注意://context.Response.Write("Hello World");// 不能夠輸出其他信息,否則瀏覽器下載的文件會有問題(文件損壞)

public class FileDownload : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        string filename = "就打算離開房間jdsk十九點.zip";// 文件名稱
        string filepath = "C:\\Attachment\\" + filename;// 文件路徑
        try
        {
            context.Response.ContentType = "application/octet-stream";// 文件類型 /application/octet-stream 表示所有文件
            context.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);// 文件名稱
            context.Response.TransmitFile(filepath);// 將文件寫入HTTP響應輸出流
            //context.Response.Write("Hello World");// 不能夠輸出其他信息,否則瀏覽器下載的文件會有問題(文件損壞)
        }
        catch (Exception e)
        {
            throw e;
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Web.config文件中配置了跨域的配置項

<configuration>

  <!--跨域請求-->
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <!--允許的請求方式-->
        <add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/>
        <!--允許的請求頭信息-->
        <add name="Access-Control-Allow-Headers" value="x-requested-with,content-type"/>
        <!--允許的請求地址 *表示所有-->
        <add name="Access-Control-Allow-Origin" value="*"/>
        <!--是否攜帶cookie信息,注意:為true時,Access-Control-Allow-Origin不允許為*-->
        <add name="Access-Control-Allow-Credentials" value="false"/>
      </customHeaders>
    </httpProtocol>
  </system.webServer>

</configuration>
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容