.net c#文件下载

一、指定服务器地址文件下载

/// <summary>
/// 下载附件 url:  http://iphoto.hucai.com/Uploads/FJFile/001448210703/2021年06月16日T22时45分30秒_remark.csv
/// </summary>
/// <param name="file_url"></param>
/// <returns></returns>
[HttpGet]
[ApiIgnore]
public FileResult DownLoadFile([Required][Url] string file_url)
{
Stream stream = null;
using (HttpClient client = new HttpClient())
{
//资源下载
var uri = new Uri(file_url);
client.BaseAddress = uri;
stream = client.GetStreamAsync(uri).GetAwaiter().GetResult();
}
return File(stream, "application/octet-stream");
}

二、当前服务器地址并转化为文件流

/// <summary>
/// 下载附件(当前服务器地址并转化为文件流)
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost]
public HttpResponseMessage DownLoadFile(OriginOrderManaApiModel.DownloadFileReq request)
{
ApiResult<object> apires = new ApiResult<object>() { code = 1 };
//string Directory = System.AppDomain.CurrentDomain.BaseDirectory;
string file_path = "/Uploads/FJFile/" + request.origin_order_num;
string file_url = HostingEnvironment.MapPath(file_path) + "\\" + request.file_name;

//var FilePath = Directory + "Uploads\\FJFile\\" + origin_order_num + "\\" + file_name;
var stream = new FileStream(file_url, FileMode.Open);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/html");
response.Content.Headers.ContentType.CharSet = "utf-8";
//response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
//{
// FileName = file_name
//};
return response;
}

三、xcel转化为文件流下载

//excel转化为文件流下载

public static System.IO.MemoryStream ExcelExport(DataTable dt)
{
NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
//设置标题样式
NPOI.SS.UserModel.ICellStyle style = book.CreateCellStyle();
NPOI.SS.UserModel.IFont font = book.CreateFont();
font.Boldweight = short.MaxValue; //字体加粗
font.FontHeightInPoints = 10; //字体大小
style.SetFont(font);
style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;

//设置正文样式
NPOI.SS.UserModel.ICellStyle style1 = book.CreateCellStyle();
style1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;

//添加一个sheet  
NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");

//给sheet1添加第一行的头部标题
NPOI.SS.UserModel.IRow row = sheet1.CreateRow(0);
for (int i = 0; i < dt.Columns.Count; i++)
{
row.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
//添加列表样式
row.GetCell(i).CellStyle = style;
}
//将数据逐步写入sheet1各个行
for (int i = 0; i < dt.Rows.Count; i++)
{
NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);
for (int j = 0; j < dt.Columns.Count; j++)
{
rowtemp.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString().Trim());
rowtemp.GetCell(j).CellStyle = style1;
}
}

//列宽自适应,只对英文和数字有效
for (int i = 0; i <= dt.Rows.Count; i++)
{
sheet1.AutoSizeColumn(i);
}
//获取当前列的宽度,然后对比本列的长度,取最大值
for (int columnNum = 0; columnNum <= dt.Columns.Count; columnNum++)
{
int columnWidth = sheet1.GetColumnWidth(columnNum) / 256; //获取当前列宽度
for (int rowNum = 1; rowNum <= sheet1.LastRowNum; rowNum++)
{
NPOI.SS.UserModel.IRow currentRow;
//当前行未被使用过
if (sheet1.GetRow(rowNum) == null)
{
currentRow = sheet1.CreateRow(rowNum);
}
else
{
currentRow = sheet1.GetRow(rowNum);
}
if (currentRow.GetCell(columnNum) != null)
{
NPOI.SS.UserModel.ICell currentCell = currentRow.GetCell(columnNum);
int length = System.Text.Encoding.Default.GetBytes(currentCell.ToString()).Length; //获取当前单元格的内容宽度
if (columnWidth < length)
{
columnWidth = length;
}
}
}
sheet1.SetColumnWidth(columnNum, (columnWidth + 3) * 256);
}
//导出后下载Excel
byte[] datas = null;
System.IO.MemoryStream ms = new System.IO.MemoryStream();
book.Write(ms);
ms.Flush();
ms.Position = 0;
datas = ms.GetBuffer();

return ms;
//return File(datas, "application/vnd.ms-excel", action + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
}
四、前端根据Url直接下载

function DownLoadFJ() {
$.ajax({
url: "/OfficeManagment/GetFileInfo",
type: "POST",
async: true,
dataType: "json",
data: { origin_order_num: '@ViewBag.OriginOrderNum'},
success: function (data) {
$('#dlFJQueueTbl').append('<tr><td style="width: 320px;">附件地址</td><td style="width: 95px;">创建时间</td><td style="width: 95px;">操作</td></tr>');
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
var file_url = data[i].file_url
var create_date = data[i].create_date;
$('#dlFJQueueTbl').append('<tr class="dlFJQueueTr"><td>' + file_url + '</td><td class="time">' + create_date + '</td><td class="dlFJQueueBtn"><a class="text-primary" href="' + file_url + '" class="btnDown" role="button">点击下载</a></td></tr>');
}
}
$('#myFile').modal('show');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('err!');
}
});
}

上一篇:解决常见情况下C++终端输入问题


下一篇:关于java实体类时间类型的格式化调整问题