MVC 实现将数据库的内容(查询结果导出)
1 (以流的形式返回给前端,导出文件),文件内容是动态查询生成的
1.1数据处理
/// <summary>
/// 输出硬盘文件,提供下载 支持大文件、续传、速度限制、资nse, string _fileName, StringBuilder data, long _speed)
{
try源占用小
/// </summary>
/// <param name="_Request">Page.Request对象</param>
/// <param name="_Response">Page.Response对象</param>
/// <param name="_fileName">下载文件名</param>
/// <param name="_data">数据(可变字符串)</param>
/// <param name="_speed">每秒允许下载的字节数</param>
/// <returns>返回是否成功</returns>
public static bool ResponseFile(HttpRequestBase _Request, HttpResponseBase _Response, string _fileName, StringBuilder data, long _speed)
{
try
{
//用BinaryReader 读取某个路径下的文件流
//FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
// BinaryReader br = new BinaryReader(myFile);
//用BinaryReader读取字节数组
StringBuilder strbData = new StringBuilder();
// byte[] shuzu = Encoding.Unicode.GetBytes(data.ToString());
##byte[] shuzu = Encoding.UTF8.GetBytes(data.ToString()); //替换上面的(解决导出csv文件表头 中文乱码的问题)**
MemoryStream myData = new MemoryStream(shuzu);
BinaryReader br = new BinaryReader(myData);
try
{
_Response.AddHeader("Accept-Ranges", "bytes");
_Response.Buffer = false;
//long fileLength = myFile.Length;
long fileLength = myData.Length;
long startBytes = 0;
int pack = 10240; //10K bytes
//int sleep = 200; //每秒5次 即5*10K bytes每秒
int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
if (_Request.Headers["Range"] != null)
{
_Response.StatusCode = 206;
string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
startBytes = Convert.ToInt64(range[1]);
}
_Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
if (startBytes != 0)
{
_Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
}
_Response.Charset = "gb2312";
_Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
_Response.AddHeader("Connection", "Keep-Alive");
_Response.ContentType = "application/octet-stream";
_Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName + ".csv", System.Text.Encoding.GetEncoding("gb2312")));
_Response.HeaderEncoding = System.Text.Encoding.GetEncoding("gb2312");//表头添加编码格式
br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;
for (int i = 0; i < maxCount; i++)
{
if (_Response.IsClientConnected)
{
_Response.BinaryWrite(br.ReadBytes(pack));
Thread.Sleep(sleep);
}
else
{
i = maxCount;
}
}
}
catch
{
return false;
}
finally
{
br.Close();
myData.Close();
}
}
catch
{
return false;
}
return true;
}
1.2 Controller层
[HttpGet]
public ActionResult ExportCard(string customerId,string contractId,string fileName)
{
CardModel cardModel = new CardModel();
List<Card> listData= cardModel.GetByInfo(customerId,contractId);
StringBuilder strData = new StringBuilder();
try
{
strData.Append("序号"+",");
strData.Append("WTP号" + ",");
strData.Append("CardId");
strData.Append("\n");
int i=0;
foreach (var item in listData)
{
strData.Append(i++);
strData.Append(",");
strData.Append(item.Code+",");
strData.Append(item.CardId);
strData.Append("\n");
}
bool flag = ImportExport.ResponseFile(Request, Response, fileName, strData,1024000);
if (true)
{
return Json(new { Success = true, Message = "导入成功!" });
}
else
{
return Json(new { Success = false, Message = "导入失败!" });
}
}
catch (Exception ex)
{
ServiceGlobal.CallInLog.Error(string.Format("ResponseError: {0}",ex.Message));
return Json(new { Success = false, Message = "导入失败!" });
}
}
1.3前端代码
location.href = "@Url.Action("ExportCard", "Card")" + "?" + "customerId=" + $("#CardCustomerId").val() + "&contractId=" + $("#ContractId").val() + "&fileName=" + $("#fileName").val();
或
var url="@Url.Action("ExportCard", "Card")" + "?" + "customerId=" + $("#CardCustomerId").val() + "&contractId=" + $("#ContractId").val() + "&fileName=" + $("#fileName").val();
var alink = document.createElement("a");
alink.download = $("#fileName").val();
alink.style.display = "none";
alink.href = url;
document.body.appendChild(alink);
alink.click();
document.body.removeChild(alink);
$('#myModal').modal('hide'); //弹出框dilog
2 <a>标签下载文件
下载的文件是在服务器端指定目录下(静态文件),也可以接受后端返回的文件流
创建a标签访问
<a href="后端接口地址"、url>下载文件</a>
触发a的click事件
3 form表单提交下载
form表单提交,接受后端返回的文件流
参考:
Web端下载文件的几种方式
[https://www.jianshu.com/p/bf0a4e3926a4]
前端接收文件流 并 下载的几种方式
[https://blog.csdn.net/weixin_33910385/article/details/88702258]