前言 文件上传有两种方式:WEB上传和FTP上传。 WEB上传就是通过点击网页中的“浏览”、“选定”、“上传”(或“确定”、“提交”)等按钮来上传文件的方式。精炼地说就是通过网
前言
文件上传有两种方式:WEB上传和FTP上传。
- WEB上传就是通过点击网页中的“浏览”、“选定”、“上传”(或“确定”、“提交”)等按钮来上传文件的方式。精炼地说就是通过网页的功能上传文件。
- FTP[File Transfer Protocol]中文译为文件传输协议,是Internet上的另一项主要服务,这项服务让使用者能通过Internet来传输各式各样的文件。FTP上传的目标服务器有一个固定的FTP地址,这个地址可以是IP地址,也可以是域名地址。一般使用专用FTP工具软件来进行FTP上传,也可以使用IE浏览器。在使用FTP上传的时候,就像在我们的电脑磁盘上复制粘贴文件一样直观。
本文主要介绍WEB上传的几种方式。
一、文件上传与下载
1.单文件上传
1、相关代码
/// <summary>
/// 上传文件
/// </summary>
/// <param name="file">上传的文件</param>
/// <param name="fold">要存储的文件夹</param>
/// <returns></returns>
[HttpGet("Upload")]
public async Task<FileMessage> UploadFileAsync(IFormFile file, string fold)
{
string fileName = file.FileName;
string path = Directory.GetCurrentDirectory() + @"/Upload/" + fold + "/";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string argumentName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + await FileHelp.GetFileSuffixAsync(file.FileName);
string fileSize = Math.Round((decimal)file.Length / 1024, 2) + "k";
string filePath = Path.Combine(path, argumentName);
try
{
using (FileStream stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
return FileMessage.CreateNew(fileName, argumentName, fileSize, 1, "文件上传成功");
}
catch (Exception e)
{
return FileMessage.CreateNew(fileName, argumentName, fileSize, -1, "文件上传失败:" + e.Message);
}
}
2、运行程序
2.多文件上传
1、相关代码
[HttpGet("UploadMul")]
public async Task<List<FileMessage>> UploadFilesAsync(IFormFileCollection files, string fold)
{
string path = Directory.GetCurrentDirectory() + @"/Upload/" + fold + "/";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
List<FileMessage> messages = new List<FileMessage>();
foreach (var file in files)
{
string fileName = file.FileName;
string argumentName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + await FileHelp.GetFileSuffixAsync(file.FileName);
string fileSize = Math.Round((decimal)file.Length / 1024, 2) + "k";
string filePath = Path.Combine(path, argumentName);
try
{
using (FileStream stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
messages.Add(FileMessage.CreateNew(fileName, argumentName, fileSize, 1, "文件上传成功"));
}
catch (Exception e)
{
messages.Add(FileMessage.CreateNew(fileName, argumentName, fileSize, -1, "文件上传失败,失败原因:" + e.Message));
}
}
return messages;
}
2、运行程序
3.文件下载
1、相关代码
[Route("api/[controller]")]
[ApiController]
public class HomeController: ControllerBase
{
private readonly string createName = "";
private readonly IWebHostEnvironment _env;
private readonly ILogger<HomeController> _logger;
public HomeController(IWebHostEnvironment env,
ILogger<HomeController> logger)
{
_env = env;
_logger = logger;
}
/// <summary>
/// 下载附件
/// </summary>
/// <param name="fileName">文件名称</param>
/// <returns></returns>
[HttpGet("download")]
public async Task<FileStreamResult> Download([FromQuery] string fileName)
{
try
{
string rootPath = _env.ContentRootPath + @"/Upload/ManageProtocolFile";
string filePath = Path.Combine(rootPath, fileName);
var stream = System.IO.File.OpenRead(filePath);
string contentType = await GetFileContentTypeAsync(fileName);
_logger.LogInformation("用户:" + createName + "下载后台客户协议附件:" + request.FileName);
return File(stream, contentType, fileName);
}
catch (Exception e)
{
_logger.LogError(e, "用户:" + createName + "下载后台客户协议附件出错,出错原因:" + e.Message);
throw new Exception(e.ToString());
}
}
}
2、运行程序
相关类库
1、获取文件后缀
/// <summary>
/// 获取文件后缀
/// </summary>
/// <param name="fileName">文件名称</param>
/// <returns></returns>
public async static Task<string> GetFileSuffixAsync(string fileName)
{
return await Task.Run(() =>
{
string suffix = Path.GetExtension(fileName);
return suffix;
});
}
2、获取ContentType属性
/// <summary>
/// 获取文件ContentType
/// </summary>
/// <param name="fileName">文件名称</param>
/// <returns></returns>
public async static Task<string> GetFileContentTypeAsync(string fileName)
{
return await Task.Run(() =>
{
string suffix = Path.GetExtension(fileName);
var provider = new FileExtensionContentTypeProvider();
var contentType = provider.Mappings[suffix];
return contentType;
});
}
3、FileMessage
public class FileMessage
{
/// <summary>
/// 原文件名称
/// </summary>
public string FileName { get; set; }
/// <summary>
/// 附件名称(协议或其他要进行数据库保存与模型绑定的命名)
/// </summary>
public string ArgumentName { get; set; }
/// <summary>
/// 文件大小(KB)
/// </summary>
public string FileSize { get; set; }
/// <summary>
/// -1:上传失败 0:等待上传 1:已上传
/// </summary>
public int FileStatus { get; set; }
/// <summary>
/// 上传结果
/// </summary>
public string UploadResult { get; set; }
/// <summary>
/// 创建实例
/// </summary>
/// <param name="fileName">原文件名称</param>
/// <param name="argumentName">(新)附件名称</param>
/// <param name="fileSize">大小</param>
/// <param name="fileStatus">文件状态</param>
/// <returns></returns>
public static FileMessage CreateNew(string fileName,
string argumentName,
string fileSize,
int fileStatus,
string uploadResult)
{
return new FileMessage()
{
FileName = fileName,
ArgumentName = argumentName,
FileSize = fileSize,
FileStatus = fileStatus,
UploadResult = uploadResult
};
}
}
【本文由:高防cdn http://www.558idc.com/gfcdn.html 复制请保留原URL】