.NET 大文件上传下载

时间:2022-04-17 17:20:28

一、文件上传

  • 配置Web.config
  <system.web>
<compilation debug="true" targetFramework="4.5.2" />
<!--<httpRuntime targetFramework="4.5.2" maxRequestLength="2147483647" executionTimeout="3600"/>-->
<httpRuntime executionTimeout="3600" maxRequestLength="2147483647" useFullyQualifiedRedirectUrl="true" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100" enableVersionHeader="true" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
</system.web>
  • cshtml前端控件
<div id="div_filemanager_list_header_upload">
<input onclick="uploadFile()" class="button" type="button" value="上传文件" />
</div>
  • 读取file,使用ajax上传
  var file = document.getElementById("input_file").files[0];
if (file.size > 2147480000)//
{
alert(
"文件不得大于2GB!");
return;
}
 //获取文件信息
var formData = new FormData();
formData.append(
"file", file);
formData.append(
"fileinfo", JSON.stringify(fileinfo));
currentAjax
= $.ajax({
url:
"/FileManager/UpLoadFile",
type:
"post",
// Form数据
data: formData,
dataType:
"text",
processData:
false,
contentType:
false,
xhr: function () {
var xhr = $.ajaxSettings.xhr();
console.log(xhr.status);
if (onmyprogress && xhr.upload) {
xhr.upload.addEventListener(
"progress", onmyprogress, false);
return xhr;
}
},
success: function (data) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
  • 后台接收文件并保存
            var files = Request.Files;
var json = Request.Form["fileinfo"];
if (files.Count > 0)
{
var file = files[0];
string fileName = file.FileName.Split('\\').Last();
string fileSaveFolder = HttpRuntime.AppDomainAppPath.ToString() + "Data\\File\\" + DateTime.Now.ToFileTime().ToString() + "\\";
tb_FileInfo fileInfo
= new tb_FileInfo();
string fileSavePath = null;//带文件名路径
//读取文件并保存
try
{
if (!Directory.Exists(fileSaveFolder)) Directory.CreateDirectory(fileSaveFolder);
fileInfo
= JsonConvert.DeserializeObject<tb_FileInfo>(json) as tb_FileInfo;
fileSavePath
= Path.Combine(fileSaveFolder, fileName);
file.SaveAs(fileSavePath);
}
catch
{
return "读取文件错误!";
}
        }

 二、下载文件


在服务器端生成文件后,前台使用window.open(url)直接访问文件。