gpt4 book ai didi

asp.net-mvc - 用于 asp.net mvc 的回形针

转载 作者:行者123 更新时间:2023-12-02 00:11:59 26 4
gpt4 key购买 nike

是否存在像 Paperclip for Rails 这样的插件?

实现自己的系统来上传文件并调整其大小真的很痛苦......

拥有模型属性会很酷,它会像这样获取参数:

型号:

[Paperclip(Sizes={thumb="100x20",big="200x40"},Path="~/public/")]
public string Image{get;set;}

查看:

Html.Editor(x=>x.Image)

here is small tutorial for rails .

最佳答案

看起来这个问题很老了,我偶然发现了它,因为它似乎还没有答案,我决定带上我的 2 美分。

我不知道 ASP.NET 是否存在这样的插件,但编写一个非常容易:

[AttributeUsage(AttributeTargets.Property)]
public class PaperClipAttribute : Attribute, IMetadataAware
{
public PaperClipAttribute(string uploadPath, params string[] sizes)
{
if (string.IsNullOrEmpty(uploadPath))
{
throw new ArgumentException("Please specify an upload path");
}

UploadPath = uploadPath;
Sizes = sizes;
}

public string UploadPath { get; private set; }
public string[] Sizes { get; private set; }

public void OnMetadataCreated(ModelMetadata metadata)
{
metadata.AdditionalValues["PaperClip"] = this;
}
}

然后为 HttpPostedFileBase 类型定义自定义模型绑定(bind)器:

public class PaperClipModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var paperClip = bindingContext.ModelMetadata.AdditionalValues["PaperClip"] as PaperClipAttribute;
if (paperClip == null)
{
return base.BindModel(controllerContext, bindingContext);
}

var uploadedFile = base.BindModel(controllerContext, bindingContext) as HttpPostedFileBase;
if (uploadedFile == null)
{
return null;
}

var uploadPath = controllerContext.HttpContext.Server.MapPath(paperClip.UploadPath);
if (!Directory.Exists(uploadPath))
{
throw new ArgumentException(string.Format("The specified folder \"{0}\" does not exist", uploadPath));
}
var sizes =
(from size in paperClip.Sizes
let tokens = size.Split('x')
select new Size(int.Parse(tokens[0]), int.Parse(tokens[1]))
).ToArray();

foreach (var size in sizes)
{
var extension = Path.GetExtension(uploadedFile.FileName);
var outputFilename = Path.Combine(
uploadPath,
Path.ChangeExtension(
string.Format("image{0}x{1}", size.Width, size.Height),
extension
)
);
Resize(uploadedFile.InputStream, outputFilename, size);
}

return base.BindModel(controllerContext, bindingContext);
}

private void Resize(Stream input, string outputFile, Size size)
{
using (var image = Image.FromStream(input))
using (var bmp = new Bitmap(size.Width, size.Height))
using (var gr = Graphics.FromImage(bmp))
{
gr.CompositingQuality = CompositingQuality.HighSpeed;
gr.SmoothingMode = SmoothingMode.HighSpeed;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.DrawImage(image, new Rectangle(0, 0, size.Width, size.Height));
bmp.Save(outputFile);
}
}
}

将在Application_Start中注册:

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();

RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
ModelBinders.Binders[typeof(HttpPostedFileBase)] = new PaperClipModelBinder();
}

我们已经完成了。剩下的都是经典的东西。

查看模型:

public class MyViewModel
{
[PaperClip("~/App_Data", "100x20", "200x40", "640x480")]
[Required(ErrorMessage = "Please select a file to upload")]
public HttpPostedFileBase Image { get; set; }
}

Controller :

public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}

[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
return Content("thanks for uploading");
}
}

查看:

@model MyViewModel

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.LabelFor(x => x.Image)
<input type="file" name="image" />
@Html.ValidationMessageFor(x => x.Image)
<input type="submit" value="Upload" />
}

关于asp.net-mvc - 用于 asp.net mvc 的回形针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5013824/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com