【问题标题】:can't use replace function when upload files API on asp.net core 2.2在 asp.net core 2.2 上上传文件 API 时无法使用替换功能
【发布时间】:2021-02-26 18:50:42
【问题描述】:

我使用 ASP.NET Core 2.2 Web API 并面临一个问题:我无法使用替换功能来更改上传时获得的选定文件的名称属性。

当我这样尝试时:

string fileName = DisplayFileName.Replace(".xlsx", "-") + Guid.NewGuid().ToString() + ".xlsx";

我收到一个错误

iform 文件不包含替换的定义,并且没有可访问的扩展方法替换接受 iformfile 的第一个参数

完整示例在这里:

[HttpPost, DisableRequestSizeLimit]
public IActionResult Upload()
{
        try
        {
            var DisplayFileName = Request.Form.Files[0];
            string fileName = DisplayFileName.Replace(".xlsx", "-") + Guid.NewGuid().ToString() + ".xlsx";
            string Month = DateTime.Now.Month.ToString();
            string DirectoryCreate = myValue1 + Month;

            Path.Combine(Directory.GetCurrentDirectory(), folderName);

            if (!Directory.Exists(DirectoryCreate))
            {
                Directory.CreateDirectory(DirectoryCreate);
            }

            if (DisplayFileName.Length > 0)
            {
                var filedata = ContentDispositionHeaderValue.Parse(Request.Form.Files[0].ContentDisposition).FileName.Trim('"');
                var dbPath = Path.Combine(DirectoryCreate, fileName);
              
                using (var stream = new FileStream(dbPath, FileMode.Create))
                {
                    Request.Form.Files[0].CopyTo(stream);
                }

                return Ok(new { dbPath });
            }
            else
            {
                return BadRequest();
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Internal server error: {ex}");
        }
}

如何解决这个问题? 样本

假设我选择文件 Developed.xlsx

然后使用替换或任何方式结果将是

开发的-sddfn78888.xlsx

【问题讨论】:

    标签: c# asp.net-mvc ado.net asp.net-core-webapi asp.net-core-2.2


    【解决方案1】:

    您可以使用System.IO.Path 从请求文件中获取文件名和文件扩展名。 改变这个 string fileName = DisplayFileName.Replace(".xlsx", "-") + Guid.NewGuid().ToString() + ".xlsx";

    string filename = Path.GetFileName(DisplayFileName.FileName);
    string fileExtension = Path.GetExtension(DisplayFileName.FileName);
    string newFileName = $"{filename}-{Guid.NewGuid().ToString()}{fileExtension}";
    

    否则,您可以将代码修改为

     string fileName = DisplayFileName.FileName.Replace(".xlsx", "-") + Guid.NewGuid().ToString() + ".xlsx";
    

    【讨论】:

      猜你喜欢
      • 2019-11-03
      • 2021-05-27
      • 2021-03-01
      • 2021-08-02
      • 1970-01-01
      • 2020-12-22
      • 1970-01-01
      • 2020-10-05
      • 2016-11-14
      相关资源
      最近更新 更多