Uploading image via ASP.NET Core Web API gets corrupted

246 views Asked by At

I'm developing an ASP.NET Core Web API that posts an image and saves it to the server.

When I using Visual Studio, it works fine and saves the image in the Pics directory.

But when uploading it to Windows VPS, it saves the file, but there is no size - it means it's corrupted.

[HttpPost]
public async Task<ActionResult<ImageFile>> PostImage([FromForm] ImageFile image)
{
    try
    {
        // string Pic = Path.GetFileNameWithoutExtension(image.AttImage.FileName);
        string path = Path.Combine(wwrootPath + "/Pics/" + RandomString(32) + ".jpg");

        // Logger.LogError("Omar1 : " + path);
        if (image.AttImage == null)
            return null;

        using (var filestream = new FileStream(path, FileMode.Create))
        {
            _= image.AttImage.CopyToAsync(filestream);
        }
                
        image.ImagePath = path;
        image.CreatedDate = DateTime.UtcNow;

        // Logger.LogError("Omar2 : "+path);

        _context.Images.Add(image);
        await _context.SaveChangesAsync();

        return image;
    }
    catch (Exception ex) 
    {
        Logger.LogError(ex.Message+" : "+ex.InnerException);
        return null; 
    }
}

enter image description here

I searched for many solutions and give the Pics directory full control permission but the problem persists.

Does anyone have any idea?

0

There are 0 answers