April 14, 2020

ASP.NET MVC 上传文件

微软示例:https://docs.microsoft.com/zh-cn/aspnet/web-api/overview/advanced/sending-html-form-data-part-2

public class UploadController : ApiController
{
    public async Task<HttpResponseMessage> PostFormData()
    {
        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);

        try
        {
            // Read the form data.
            await Request.Content.ReadAsMultipartAsync(provider);

            // This illustrates how to get the file names.
            foreach (MultipartFileData file in provider.FileData)
            {
                Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                Trace.WriteLine("Server file path: " + file.LocalFileName);
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }

}

也可以在 Action 中使用 HttpContext.Current.Request.Files 来获取提交的文件。

高级

  • Base64 编码的文件名
/// <summary>
/// 生成文件名。
/// </summary>
/// <param name="originName"></param>
/// <returns></returns>
private string GenerateFileName(string originName)
{
    var nonce = new Random().Next(100000, 999999);
    var now = DateTime.Now.ToString("yyyyMMddhhmmssfff");
    var dotIndex = originName.LastIndexOf('.');
    var extensionLength = originName.Length - dotIndex;

    var fileExtension = originName.Remove(0, dotIndex);
    var fileNameWithoutExtension = originName.Remove(dotIndex, extensionLength);

    var fileName = $"{nonce}{now}{Guid.NewGuid().ToString().Replace("-", "")}{fileNameWithoutExtension}";
    var fileNameBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(fileName)).Replace('/', '-');

    return $"{fileNameBase64}{fileExtension}";
}