关于C#文件的上传和下载,文件流相关

发布时间 2023-12-20 19:10:19作者: x欣x

文件的上传和下载 控制器:
/// <summary>
/// 上传web文件
/// </summary>
/// <param name="files"></param>
/// <param name="wellName">井名</param>
/// <param name="userName">用户名</param>
/// <param name="directoryID">全级目录id</param>
/// <returns></returns>
[HttpPost("UpLoadFile")]
//限制最大单个文件为2G
[RequestFormLimits(MultipartBodyLengthLimit = 2147483648)]
[RequestSizeLimit(2147483648)]
public bool UpLoadFile([FromForm] IFormFileCollection files, string wellName, string userName,string directoryID)
{
string errorMsg = null;
if (files == null || files.Count == 0)
{
throw new ApiException((int)ResultCode.FileException, "请选择上传文件");
}
List<string> list = new List<string>();
ResultCode code = _FileOperationService.UpLoadFile(files[0], wellName, userName, directoryID, ref errorMsg);
//返回文件的相对路径
if (code != ResultCode.OK)
{
throw new ApiException((int)code, errorMsg);
}
return true;
}
/// <summary>
/// 根据查询到的id下载文件
/// </summary>
/// <returns></returns>
[HttpGet("DownloadFile")]
public ActionResult DownloadFile(string id)
{
string errorMsg = null;
HttpResponseMessage action = null;
ResultCode code = _FileOperationService.DownloadFile(id, out byte[] infbytes, out string fileName, ref errorMsg);
//返回文件的相对路径
if (code == ResultCode.OK)
{
return File(infbytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
}
throw new ApiException((int)code, errorMsg);
}
实现:
-- public ResultCode UpLoadFile(IFormFile formFile, string wellName, string userName,string directoryID, ref string errorMsg)
{
try
{
string remark = string.Empty;
string directoryName = string.Empty;
string code = MD5Helper.MD5Encrypt32(DateTime.Now + formFile.FileName);
long datasize = formFile.Length / 1024;
//写表,返回id
cd_tot_file_003 file = new cd_tot_file_003();
file.FILE_NAME = formFile.FileName;
file.CREATE_TIME = DateTime.Now;
file.FILE_CODE = code;
file.FILE_LENGTH = datasize.ToString() + " KB";
file.WID = wellName;
file.CREATE_USER = userName;
// file.VERSION = 0;
file.DEL_FLAG = 0;
// file.FILE_ADDRESS = code + "0" + formFile.FileName;
var db = ContextManager.GetDbContext(DBTypeString.DB_BASE);
if(directoryID != null)
{
string[] stringArr = directoryID.Split(',');//将字符串转换为数组
string[] arrNew = stringArr.Reverse().Take(1).Reverse().ToArray();//获取后1个数组元素
string strNew = string.Join(",", arrNew);//再次将数组转换为以,分割的字符串
var dirRow = db.Queryable<cd_cfg_directory_001>().Where(it => it.ID == int.Parse(strNew)).First();
directoryName = dirRow.NAME;
remark = "文件保存在目录树的全路径id:" + directoryID;
}
long id = db.Insertable<cd_tot_file_003>(file).ExecuteReturnBigIdentity();
//操作文件
// string code = MD5Helper.MD5Encrypt32(DateTime.Now + name);
string extension = Path.GetExtension(formFile.FileName);
if (!string.IsNullOrEmpty(extension))
{
extension = extension.TrimStart('.');
}
string newFileName = jointFileName(formFile.FileName, new string[] { id.ToString() }, "_"); // formFile.FileName.Replace(extension, "_" + id + extension); //
string datetime= DateTime.Now.ToString("d");
var finalFilePath = Path.Combine(modelFilePath, datetime, newFileName);//最终的文件名
var newFilePath = finalFilePath.Replace(FilePathHead, "");
if (System.IO.File.Exists(finalFilePath))
{
//throw new ApiException((int)ResultCode.FileExists, "文件已存在");
}
string DirPath = Path.GetDirectoryName(finalFilePath);
if (!Directory.Exists(DirPath))
{
Directory.CreateDirectory(DirPath);
}
//StreamReader reader = new StreamReader(formFile.OpenReadStream());
//从流的当前位置到末尾读取所有字符,如果当前位置位于流的末尾,则返回空字符串“”
//String content = reader.ReadToEnd();
using (FileStream fs = System.IO.File.Create(finalFilePath))
{
// 复制文件
formFile.CopyTo(fs);
// 清空缓冲区数据
fs.Flush();
}
--------------------
下载; public ResultCode DownloadFile(string id, out byte[] infbytes, out string fileName, ref string errorMsg)
{
infbytes = null ;
fileName = string.Empty;
if (string.IsNullOrEmpty(id))
{
errorMsg = "id不能为空";
throw new BizException((int)ResultCode.CheckException, errorMsg);
}
try
{
var db = ContextManager.GetDbContext(DBTypeString.DB_BASE);
var dirRow = db.Queryable<cd_tot_file_003>().Where(it => it.ID == int.Parse(id)).First();
string fileAddress = dirRow.FILE_ADDRESS;
fileName = dirRow.FILE_NAME;
string filePath = FilePathHead + fileAddress;
//创建d:\file.txt的FileStream对象
FileStream fstream = new FileStream(filePath, FileMode.OpenOrCreate);
infbytes = new byte[fstream.Length];
//设置流当前位置为文件开始位置
fstream.Seek(0, SeekOrigin.Begin);

//将文件的内容存到字节数组中(缓存)
fstream.Read(infbytes, 0, infbytes.Length);
string result = Encoding.UTF8.GetString(infbytes);
Console.WriteLine(result);
if (fstream != null)
{
//清除此流的缓冲区,使得所有缓冲的数据都写入到文件中
fstream.Flush();
fstream.Close();
}

return ResultCode.OK;
}
catch (BizException ex)
{
errorMsg = ex.msg;
log.Error("[FileOperationService.AddDirectoryTreeData] BizException error," + errorMsg + ",id:" + JsonConvert.SerializeObject(id), ex);
return (ResultCode)ex.code;
}
catch (Exception ex)
{
errorMsg = EnvironmentConfiguration.UserEnvironment ? EnvironmentConfiguration.ErrorMsg : ex.Message;
log.Error("[FileOperationService.AddDirectoryTreeData] Exception error," + errorMsg + ",id:" + JsonConvert.SerializeObject(id), ex);
return ResultCode.InternalServerError;
}
}
___________________________________________________________________________________________________________________________________________________________
文件流处理关键代码
//创建d:\file.txt的FileStream对象
FileStream fstream = new FileStream(@"d:\file.txt", FileMode.OpenOrCreate);
byte[] bData = Encoding.UTF8.GetBytes("test filestream");
//设置流当前位置为文件开始位置
fstream.Seek(0, SeekOrigin.Begin);

//将字节数组中的内容写入文件
fstream.Write(bData, 0, bData.Length);
if (fstream != null)
{
//清除此流的缓冲区,使得所有缓冲的数据都写入到文件中
fstream.Flush();
fstream.Close();
}