1

I'm trying to post an uploaded image from the front-end using aurelia to a asp.net mvc. Is there someway I can save the image received in as png format in a folder on the server?

Javascript method from where I'm posting the image data(files is the uploaded image and id is the unique image ID that I need to use for the file name)

saveImage(files,id) {
        var form = new FormData()
        form.append('file', files)
        form.append('ID', id)

        this.http.fetch('/api/Employees', {
            method: 'post',
            body: form
        })

        return true;
    }

ImagesController(Asp.net MVC)

using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace SPAproject.Controllers
{
    public class ImagesController : Controller
    {
        [HttpPost, Route("api/[controller]")]
        public async Task<IActionResult> SaveImage()
        {
            try
            {
                var form = await Request.ReadFormAsync();
                var file = form.Files.First();

                var id = form.ElementAt(1);
                var path = "/images/" + id + ".png";
                Stream stream = file.OpenReadStream();

                return Ok(true);
            }
            catch (Exception ex)
            {
                var originalMessage = ex.Message;

                while (ex.InnerException != null)
                    ex = ex.InnerException;
                return BadRequest($"{originalMessage} | {ex.Message}");
            }
        }
    }
}
}

2 Answers 2

1
string fileName = string.Format("{0}{1}", id, ".png");
var serverPath = Server.MapPath("~/images");
var path = Path.Combine(serverPath, fileName);

using (Stream inputStream = file.OpenReadStream())
using (var outputStream = new FileStream(path, FileMode.Create))
{
    // dump a stream to a file
    inputStream.CopyTo(outputStream);
}
Sign up to request clarification or add additional context in comments.

Comments

1

I assume you use ASP.NET Core, not ASP.NET(using Microsoft.AspNetCore.Mvc;)

You can use new class in asp.net core, IFormFile. It simplifies the stream operations.

[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
    long size = files.Sum(f => f.Length);

    // full path to file in temp location
    var filePath = Path.GetTempFileName();

    foreach (var formFile in files)
    {
        if (formFile.Length > 0)
        {
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await formFile.CopyToAsync(stream);
            }
        }
    }

    // process uploaded files
    // Don't rely on or trust the FileName property without validation.

    return Ok(new { count = files.Count, size, filePath});
}

Also, you can find the full documentation here. File uploads in ASP.NET Core:

1 Comment

I'm using an adapted version of that code for the back-end which I'm assuming is working as my error turned from an error code 400 to a 500 one. So I'm concluding that my aurelia fetch request is the wrong part. Do you know a way how I can solve this ? using a catch with the fetch is logging an error and no image is being saved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.