前端:Vue+axios+Element UI
后端:C# .Net 一般處理程序(ashx)
上傳文件
前端代碼 Element UI
使用Element UI的el-upload組件
- action=http://localhost:8070/FileUpload.ashx?userid=27777(請(qǐng)求的地址)
- 如果使用http-request(自定義上傳)暫未找到進(jìn)度條的控制辦法
- 上傳大文件報(bào) HTTP Error 404.13 - Not Found 的解決辦法
<!-- action:文件上傳的URL地址(必需)../../../../../ISV/AttachmentSite/FileUpload.ashx -->
<!-- drag:是否啟用拖拽上傳 -->
<!-- multiple:是否支持多選文件 -->
<!-- limit:最大允許上傳個(gè)數(shù) -->
<!-- file-list:上傳的文件列表 -->
<!-- http-request:自定義上傳行為:http-request="FileUploadRequest"-->
<!-- on-success:文件上傳成功時(shí)的鉤子 -->
<!-- on-error:文件上傳失敗時(shí)的鉤子-->
<!-- before-upload:文件上傳之前的鉤子,返回false終止上傳-->
<!-- on-change:文件狀態(tài)改變時(shí)的鉤子裹赴,添加文件喜庞、上傳成功和上傳失敗時(shí)都會(huì)被調(diào)用-->
<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>點(diǎn)擊上傳</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"];// 單個(gè)文件
HttpFileCollection Files = HttpContext.Current.Request.Files;// 多個(gè)文件
string AbsolutePath = ConfigurationManager.AppSettings["IsAbsolutePath"];
bool IsAbsolutePath = Convert.ToBoolean(AbsolutePath);// 是否啟用絕對(duì)路徑
string FilePath = "";// 文件路徑
if (IsAbsolutePath)
{
FilePath = ConfigurationManager.AppSettings["FilePath"].ToString();// 絕對(duì)文件路徑
}
else
{
FilePath = HttpContext.Current.Request.PhysicalApplicationPath+ "\\Attachment\\";// 獲取應(yīng)用程序的根路徑
//FilePath = FilePath.Replace("AttachmentSite", "Attachment");// 將站點(diǎn)地址替換為文件地址
}
// 判斷文件路徑是否存在
if (!System.IO.Directory.Exists(FilePath))
{
System.IO.Directory.CreateDirectory(FilePath);//創(chuàng)建文件夾
}
// 保存文件
Dictionary<string, string> dicFilePath = new Dictionary<string, string>();// 返回結(jié)果字典
foreach (string strFile in Files)
{
HttpPostedFile File = Files[strFile];// 用key獲取單個(gè)文件對(duì)象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文件中配置了跨域、上傳文件限制大小延都、上傳文件路徑的配置項(xiàng)
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5.2"/>
<httpRuntime targetFramework="4.5.2" maxRequestLength="1048576000" executionTimeout="3600"/>
</system.web>
<!--跨域請(qǐng)求-->
<system.webServer>
<httpProtocol>
<customHeaders>
<!--允許的請(qǐng)求方式-->
<add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/>
<!--允許的請(qǐng)求頭信息-->
<add name="Access-Control-Allow-Headers" value="x-requested-with,content-type"/>
<!--允許的請(qǐng)求地址 *表示所有-->
<add name="Access-Control-Allow-Origin" value="*"/>
<!--是否攜帶cookie信息,注意:為true時(shí),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>
<!--是否啟用絕對(duì)路徑-->
<add key="IsAbsolutePath" value="false" />
<!--絕對(duì)文件路徑-->
<add key="FilePath" value="C:\Attachment\" />
</appSettings>
</configuration>
下載文件(單個(gè)文件)
前端代碼 Vue+axios
按鈕調(diào)用methods中的FileDownloadRequest方法
就打算離開房間 jdsk 十九點(diǎn).zip 是文件名稱(有中文有空格)
// 下載文件
FileDownloadRequest: function () {
// 發(fā)起Ajax請(qǐng)求
axios({
method: 'post',
url: 'http://localhost:8022/FileDownload.ashx',// 服務(wù)器CRM附件站點(diǎn)
responseType: 'blob'
})
// 下載文件成功
.then(res => {
console.log(res);
//對(duì)于<a>標(biāo)簽雷猪,只有 Firefox 和 Chrome(內(nèi)核) 支持 download 屬性,IE10+支持blob但是依然不支持download
if ('download' in document.createElement('a')) {//支持a標(biāo)簽download的瀏覽器
let url = window.URL.createObjectURL(res.data);//為文件流創(chuàng)建構(gòu)建下載鏈接
let link = document.createElement('a');//創(chuàng)建a標(biāo)簽
link.style.display = 'none';
link.href = url;
link.setAttribute('download', "就打算離開房間 jdsk 十九點(diǎn).zip");//設(shè)置a標(biāo)簽的下載動(dòng)作和下載文件名 /row.new_filefullname
document.body.appendChild(link);
link.click();//執(zhí)行下載
document.body.removeChild(link);//釋放標(biāo)簽
}
else {
//其他瀏覽器
navigator.msSaveBlob(res.data, "就打算離開房間 jdsk 十九點(diǎn).zip");
}
})
// 下載文件失敗
.catch(err => {
console.log(err);
this.$message.error({ message: err.message });
})
},
后端代碼 C# (ashx)
C# TransmitFile 方式下載
特別注意://context.Response.Write("Hello World");// 不能夠輸出其他信息晰房,否則瀏覽器下載的文件會(huì)有問題(文件損壞)
public class FileDownload : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string filename = "就打算離開房間jdsk十九點(diǎn).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響應(yīng)輸出流
//context.Response.Write("Hello World");// 不能夠輸出其他信息求摇,否則瀏覽器下載的文件會(huì)有問題(文件損壞)
}
catch (Exception e)
{
throw e;
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
Web.config文件中配置了跨域的配置項(xiàng)
<configuration>
<!--跨域請(qǐng)求-->
<system.webServer>
<httpProtocol>
<customHeaders>
<!--允許的請(qǐng)求方式-->
<add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/>
<!--允許的請(qǐng)求頭信息-->
<add name="Access-Control-Allow-Headers" value="x-requested-with,content-type"/>
<!--允許的請(qǐng)求地址 *表示所有-->
<add name="Access-Control-Allow-Origin" value="*"/>
<!--是否攜帶cookie信息,注意:為true時(shí),Access-Control-Allow-Origin不允許為*-->
<add name="Access-Control-Allow-Credentials" value="false"/>
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>