在ASP.NET MVC中保存用户上传的图像

时间:2019-02-24 10:45:43

标签: c# asp.net-mvc image aurelia

我正在尝试使用aurelia从前端将上传的图像发布到asp.net mvc。有什么办法可以将以png格式接收的图像保存在服务器上的文件夹中吗?

我从中发布图像数据的Javascript方法(文件是上传的图像,id是我需要用于文件名的唯一图像ID)

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 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:1)

我假设您使用的是ASP.NET Core,而不是ASP.NET(使用Microsoft.AspNetCore.Mvc;)

您可以在asp.net核心IFormFile中使用新类。简化了流操作。

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

此外,您还可以在此处找到完整的文档。 File uploads in ASP.NET Core