using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using JYRS.Util;
namespace JYRS.Utils
{
public class FileHelper
{
/// <summary>
/// 将文件名解析成文件的上传路径
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="path">文件路径</param>
/// <returns path>文件在服务器上的路径</returns>
public static String transPath(string fileName, string path)
{
createDir(path);
//取服务器时间+8位随机码作为部分文件名,确保文件名无重复
string nowStr = DateTime.Now.ToString("yyyyMMddhhmmssff") + Global.CreateRandomCode(8);
// 去掉后缀的文件名
string fileNameStr = fileName.Substring(0, fileName.LastIndexOf("."));
// 文件后缀
String suffix = fileName.Substring(fileName.LastIndexOf(".") + 1);
if (fileName.Trim() != "")
{
// 如果名称不为"",说明该文件存在,否则说明该文件不存在
path += "\\" + fileNameStr + nowStr + "." + suffix;// 定义上传路径
}
return path;
}
/// <summary>
/// 创建文件目录
/// </summary>
/// <param name="root">根目录</param>
/// <returns ></returns>
private static void createDir(String root)
{
// 检查目录
if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(root)))
{
Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(root));
}
}
/// <summary>
/// 根据文件在服务器上的路径下载文件,此处采用的是WebAPI的方式进行文件下载,下载成功后可自定义文件的保存路径
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="path">文件路径</param>
/// <returns></returns>
public static HttpResponseMessage download(string fileName, string path)
{
try
{
var stream = new FileStream(path, FileMode.Open);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fileName
};
return response;
}
catch
{
return new HttpResponseMessage(HttpStatusCode.NoContent);
}
}
}
}
[HttpGet]
public HttpResponseMessage UploadAndDownload()
{
//文件上传到服务器上的根目录
string root = System.Web.Hosting.HostingEnvironment.MapPath(@"~/upload");
string fileName = "测试.docx";
//解析文件在服务器上的上传路径
string path = FileHelper.transPath(fileName, root);
//获取要上传的文件
var files = HttpContext.Current.Request.Files;
HttpPostedFile file = HttpContext.Current.Request.Files[0];
//保存文件
file.SaveAs(System.Web.HttpContext.Current.Server.MapPath(path));
//下载word文件
return FileHelper.download(fileName, path);
}
<a href="http://localhost:60179/api/CeshiController/UploadAndDownload" rel="external nofollow" "> 导出 </a>
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有