1

在这里我拿了这个,因为我正在发送给你,请看一次,请检查一次,这是做这项工作的正确方法

 UploadController  class file


 public class UploadController : ApiController
    {


    public async Task<HttpResponseMessage> Post()
    {
        if (!Request.Content.IsMimeMultipartContent("form-data"))
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        var uploadFolder = HostingEnvironment.MapPath("~/app_data");
        uploadFolder = Path.Combine(uploadFolder, DateTime.Now.ToString("yyyyMMddhhmmssfff"));
        Directory.CreateDirectory(uploadFolder);
        var streamProvider = new PreserveFilenameMultipartFileStreamProvider(uploadFolder);

        var parts = await Request.Content.ReadAsMultipartAsync(streamProvider);
        foreach (var uploadedFile in Directory.GetFiles(uploadFolder))
        {
            var thumbnail = Path.Combine(uploadFolder, "thumb-" + Path.GetFileName(uploadedFile));
            var medium = Path.Combine(uploadFolder, "medium-" + Path.GetFileName(uploadedFile));
            var large = Path.Combine(uploadFolder, "large-" + Path.GetFileName(uploadedFile));
            ImageTools.Resize(uploadedFile, thumbnail, 100, 100);
            ImageTools.Resize(uploadedFile, medium, 200, 200);
            ImageTools.Resize(uploadedFile, large, 300, 300);
        }

        return Request.CreateResponse(HttpStatusCode.Accepted);

我在models文件夹中为imagetools制作了一个单独的文件

 public class imageTools
    {
        public static void Resize(string original, string output, int width, int height)
        {
            using (var image = Image.FromFile(original))
            using (var thumbnail = new Bitmap(width, height))
            using (var graphics = Graphics.FromImage(thumbnail))
            {
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                graphics.CompositingQuality = CompositingQuality.HighQuality;

                graphics.DrawImage(image, 0, 0, width, height);

                ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
                EncoderParameters encoderParameters;
                encoderParameters = new EncoderParameters(1);
                encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
                thumbnail.Save(output, info[1], encoderParameters);
            }
        }
    }

我又拿了一个文件名

  PreserveFilenameMultipartFileStreamProvider




    public class PreserveFilenameMultipartFileStreamProvider : MultipartFileStreamProvider
    {
        public PreserveFilenameMultipartFileStreamProvider(string rootPath)
            : base(rootPath)
        {
        }

        public override string GetLocalFileName(HttpContentHeaders headers)
        {
            return headers.ContentDisposition.FileName.Replace("\"", "");
        }
    }

最后是我的布局页面

     @using (Html.BeginRouteForm("DefaultApi", new { httproute = "", controller = "images" }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="image" multiple="multiple" accept="image/*" />
    <button type="submit">Upload</button>
}
4

1 回答 1

2

您可以使用ImageResizer 包。或者您也可以自己实现图像大小调整


更新:这是一个示例,您可以使用它来调整 Web API 控制器中上传的图像的大小。

您可以先编写一个使用 GDI+ 的 Resize 方法,如我链接到的上一篇文章所示:

public static class ImageTools
{
    public static void Resize(string original, string output, int width, int height)
    {
        using (var image = Image.FromFile(original))
        using (var thumbnail = new Bitmap(width, height))
        using (var graphics = Graphics.FromImage(thumbnail))
        {
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.SmoothingMode = SmoothingMode.HighQuality;
            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
            graphics.CompositingQuality = CompositingQuality.HighQuality;

            graphics.DrawImage(image, 0, 0, width, height);

            ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
            EncoderParameters encoderParameters;
            encoderParameters = new EncoderParameters(1);
            encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
            thumbnail.Save(output, info[1], encoderParameters);
        }
    }
}

然后是一个自定义MultipartFileStreamProvider,它将保留最初上传的文件名:

public class PreserveFilenameMultipartFileStreamProvider : MultipartFileStreamProvider
{
    public PreserveFilenameMultipartFileStreamProvider(string rootPath): base(rootPath)
    {
    }

    public override string GetLocalFileName(HttpContentHeaders headers)
    {
        return headers.ContentDisposition.FileName.Replace("\"", "");
    }
}

最后你可以有一个 API 控制器来接收上传的图像,将它们存储在App_Data文件夹中,并通过调整它们的大小来生成不同的格式:

public class ImagesController : ApiController
{
    public async Task<HttpResponseMessage> Post()
    {
        if (!Request.Content.IsMimeMultipartContent("form-data"))
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        var uploadFolder = HostingEnvironment.MapPath("~/app_data");
        uploadFolder = Path.Combine(uploadFolder, DateTime.Now.ToString("yyyyMMddhhmmssfff"));
        Directory.CreateDirectory(uploadFolder);
        var streamProvider = new PreserveFilenameMultipartFileStreamProvider(uploadFolder);

        await Request.Content.ReadAsMultipartAsync(streamProvider);
        foreach (var uploadedFile in Directory.GetFiles(uploadFolder))
        {
            var thumbnail = Path.Combine(uploadFolder, "thumb-" + Path.GetFileName(uploadedFile));
            var medium = Path.Combine(uploadFolder, "medium-" + Path.GetFileName(uploadedFile));
            var large = Path.Combine(uploadFolder, "large-" + Path.GetFileName(uploadedFile));
            ImageTools.Resize(uploadedFile, thumbnail, 100, 100);
            ImageTools.Resize(uploadedFile, medium, 200, 200);
            ImageTools.Resize(uploadedFile, large, 300, 300);
        }

        return Request.CreateResponse(HttpStatusCode.Accepted);
    }
}

最后,您可以拥有一个允许用户上传图片的 HTML 表单:

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @using (Html.BeginRouteForm("DefaultApi", new { httproute = "", controller = "images" }, FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <input type="file" name="image" multiple="multiple" accept="image/*" />
        <button type="submit">Upload</button>
    }
</body>  
</html>

更新 2:

看来您使用的是 .NET 4.0。这是ImagesController适用于 .NET 4.0 的修订版:

public class ImagesController : ApiController
{
    public Task<HttpResponseMessage> Post()
    {
        if (!Request.Content.IsMimeMultipartContent("form-data"))
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        var uploadFolder = HostingEnvironment.MapPath("~/app_data");
        uploadFolder = Path.Combine(uploadFolder, DateTime.Now.ToString("yyyyMMddhhmmssfff"));
        Directory.CreateDirectory(uploadFolder);
        var streamProvider = new PreserveFilenameMultipartFileStreamProvider(uploadFolder);

        return Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
        {
            foreach (var uploadedFile in Directory.GetFiles(uploadFolder))
            {
                var thumbnail = Path.Combine(uploadFolder, "thumb-" + Path.GetFileName(uploadedFile));
                var medium = Path.Combine(uploadFolder, "medium-" + Path.GetFileName(uploadedFile));
                var large = Path.Combine(uploadFolder, "large-" + Path.GetFileName(uploadedFile));
                ImageTools.Resize(uploadedFile, thumbnail, 100, 100);
                ImageTools.Resize(uploadedFile, medium, 200, 200);
                ImageTools.Resize(uploadedFile, large, 300, 300);
            }
            return Request.CreateResponse(HttpStatusCode.Accepted);
        });
    }
}
于 2012-09-25T09:36:05.300 回答