Asp.net核心文件上传

时间:2018-10-02 17:40:15

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

当我保存图像时,图像成功保存到数据库中,但是它需要这样的完整图像路径:C:\ Users .... \ Uploads \ employee.jpg我不希望这样,我需要像这样保存图像路径这个〜Uploads \ employee.jpg以及特定的文件夹和相同的路径应该保存在数据库中,如果有人在保存正确的路径后向我显示我如何查看该图像。因为这个我有错误:

“不允许加载本地资源:file:/// C:/ ......”

谢谢!

我的代码:

[HttpPost]
public async Task<IActionResult> Create(Photos photos)
    {
        if (ModelState.IsValid)
        {
            var filePath = 
            Path.Combine(_appEnvironment.ContentRootPath,
            "Uploads", photos.FormFile.FileName);
            photos.PhotoPath = filePath;

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await photos.FormFile.CopyToAsync(stream);
            }

            _context.Add(photos);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        ViewData["NewsId"] = new SelectList(_context.News, "NewsId", 
        "NewsBigTitle", photos.NewsId);
        return View(photos);
    }

2 个答案:

答案 0 :(得分:3)

分解代码:

var localPath = Path.Combine("Upload", "file.jpg");

var fullPath = Path.Combine(_appEnvironment.ContentRootPath, localPath);

localPath保存到PhotoPath

修改

好吧,现在在视图中显示PhotoPath,并将其定位为文件流操作。

[HttpGet("path/{image}")]
public FileStreamResult Image(string image)
{
    var result = new FileStreamResult(new FileStream(
                  Path.Combine(_appEnvironment.ContentRootPath, image),
                  FileMode.Open,
                  FileAccess.Read), "image/<your_mime>");
    return result;
}

我认为最好的方法是使用以下格式的http://example.com/path/image.jpg创建一个新字符串并将其绑定到src

您不能使用以下命令来定位动态添加的文件:~/path/image.jpg作为来源。

答案 1 :(得分:0)

确保已在IFileProvider类的Uploads方法中配置Configure指向您的Startup文件夹:

app.UseStaticFiles(); // Default one

// Adding one more location - folder named `Uploads` to be a custom static files folder. 
// The `Uploads` folder is available in the content root directory of the application (where your `Controllers` folder. 
// You can point it of course inside `wwwroot` - use `env.WebRootPath` instead)

app.UseStaticFiles(new StaticFileOptions {
    FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Uploads")),
    RequestPath = new PathString("/Uploads")
});

完成此操作后,您应该可以在控制器操作中以这种方式上传文件:

var filePath = Path.Combine(_environment.ContentRootPath, "Uploads", photos.FormFile.FileName);

using (var stream = new FileStream(filePath, FileMode.Create))
{
    await photos.FormFile.CopyToAsync(stream);
}