繁体   English   中英

Asp.net核心文件上传

[英]Asp.net Core File Upload

当我保存图像时,图像成功保存到数据库中,但是它需要完整的图像路径,例如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);
    }

分解代码:

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

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

localPath保存到PhotoPath

编辑

Okey,现在在视图中显示您的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作为源。

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

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM