文件存储.net核心

时间:2020-04-22 14:50:20

标签: c# asp.net-core-webapi

我正在使用项目内部的文件夹上传文件。

[HttpPost, DisableRequestSizeLimit]
public IActionResult Upload()
{
    try
    {
        var file = Request.Form.Files[0];
        var folderName = Path.Combine("Resources", "Images");
        var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);

        if (file.Length > 0)
        {
            var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
            var fullPath = Path.Combine(pathToSave, fileName);
            var dbPath = Path.Combine(folderName, fileName);

            using (var stream = new FileStream(fullPath, FileMode.Create))
            {
                file.CopyTo(stream);
            }

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

我想知道当我们为客户提供新更新时是否存在丢失此文件的风险。 如果有更好的解决方案,可以使用.net core上传文件并随后获得文件链接,请告诉我:)

2 个答案:

答案 0 :(得分:1)

我想知道当我们为客户提供新更新时是否存在丢失此文件的风险

部署应用程序意味着您将把新的可执行文件(dll)和其他存储在git中的文件复制到运行旧版本的位置。风险是,您做错了并删除数据目录。

那是说:您不应该将用户数据与可执行文件或应用程序中的其他文件(例如HTML中使用的图像,...)一起保存。如果数据明确分开,则处理(备份,部署等)会容易得多。

如果有更好的解决方案

解决方案:将其保存在管理员可以配置的文件夹中。可以使用所谓的选项:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.1

您将获得一个存储路径的类

public class StorageOptions {
   public string BasePath {get;set;}
}

答案 1 :(得分:0)

所以最后我决定使用此代码使用“ aws S3存储桶”

PutObjectResponse response = null;

            using (var stream = new MemoryStream(fileBytes))
            {
                var request = new PutObjectRequest
                {
                    BucketName = bucket,
                    Key = "folder/" + fileName,
                    InputStream = stream,
                    ContentType = file.ContentType,
                    CannedACL = S3CannedACL.PublicRead,
                };

                response = await client.PutObjectAsync(request);
            };

正如您在评论中提到的,我可以在文件后面获得链接