.net c#文件下载
2021/9/10 20:06:47
本文主要是介绍.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!');
}
});
}
这篇关于.net c#文件下载的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#
- 2024-01-24Advanced .Net Debugging 1:你必须知道的调试工具
- 2024-01-24.NET集成IdGenerator生成分布式全局唯一ID