Reputation: 13
In postman it returns:
Cannot access a closed File.
I want to return profile picture with path saved to database while adding picture which is saved in wwwroot folder on server. It always returns "Cannot access a closed file". I don't know why. If needed I will put code from adding profile picture.
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);
}
}
Upvotes: -1
Views: 85
Reputation: 13
Just removed using statement because it was closing file before it was actually sent to frontend
Upvotes: 0