前端:Vue+axios+Element UI
后端:C# .Net 一般处理程序(ashx)
上传文件
前端代码 Element UI
使用Element UI的el-upload组件
- action=http://localhost:8070/FileUpload.ashx?userid=27777(请求的地址)
- 如果使用http-request(自定义上传)暂未找到进度条的控制办法
- 上传大文件报 HTTP Error 404.13 - Not Found 的解决办法
<!-- 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>