不能访问已关闭的文件



in postman it return Cannot access a closed File。我想返回与路径保存到数据库的个人资料图片,同时添加图片保存在服务器上的wwwroot文件夹。它总是返回无法访问已关闭的文件。我不知道为什么。如果需要,我会把代码从添加头像。

public async Task<IActionResult> GetProfilePicture([FromQuery] string userId)
{
FileStreamResult file;
if (userId == null)
return BadRequest("Something went wrong");
enter code here
// searching for user to get picture path that are saved into database
var userPP = await _context.Users.FindAsync(userId);
if (userPP == null)
return BadRequest("Something went wrong! Try again");
// getting extension from file path
var ext = Path.GetExtension(userPP.ProfilePicture);

string contentType;
// sending file with right contentType depending on extension
switch (ext)
{
case ".jpg":
case ".jpeg":
contentType = "image/jpeg";
break;
case ".png":
contentType = "image/png";
break;
case ".gif":
contentType = "image/gif";
break;
default:
contentType = "application/octet-stream";
break;
}
//opening file stream to get image
using (var fs = new FileStream(userPP.ProfilePicture, FileMode.Open, FileAccess.Read))
{

file = File(fs, contentType);
return Ok(file);
}
}

刚刚删除了using语句,因为它在发送到前端之前关闭了文件

最新更新