从公共静态字符串

时间:2018-04-23 12:44:30

标签: c# asp.net .net asp.net-mvc model-view-controller

是否有一种简单的方法可以将公共静态字符串结果提供给控制器。

因此,当您上传图像时,我会尝试这样做,它会调整大小。 我在我的工具箱中制作了以下代码

public static string ImageUpload(HttpPostedFileBase file, string SubFolder)
{
    Guid gi = Guid.NewGuid();
    string extension = Path.GetExtension(file.FileName);

    using (var image = Image.FromStream(file.InputStream, true, true))
    {
        var thumbWidth = 700;
        var thumbHeight = 700;
        if (image.Width < image.Height)
        {
            //portrait image  
            thumbHeight = 640;
            var imgRatio = (float)thumbHeight / (float)image.Height;
            thumbWidth = Convert.ToInt32(image.Width * imgRatio);
        }
        else
        if (image.Height < image.Width)
        {
            //landscape image  
            thumbWidth = 960;
            var imgRatio = (float)thumbWidth / (float)image.Width;
            thumbHeight = Convert.ToInt32(image.Height * imgRatio);
        }

        using (var thumb = image.GetThumbnailImage(
            thumbWidth,
            thumbHeight,
            () => false,
            IntPtr.Zero))
        {
            var jpgInfo = ImageCodecInfo.GetImageEncoders()
                .Where(codecInfo => codecInfo.MimeType == "image/jpeg").First();

            using (var encParams = new EncoderParameters(1))
            {
                string thumbPath = "~/Content/admin/images/" + SubFolder;
                bool isExists = System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(thumbPath));

                if (!isExists)
                {
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(thumbPath));
                }

                var thumbPathFull = Path.Combine(HttpContext.Current.Server.MapPath(thumbPath), gi + extension);
                string newfileurl = "/Content/admin/images/" + SubFolder + gi + extension;
                long quality = 1500;
                encParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                thumb.Save(thumbPathFull, jpgInfo, encParams);
                return newfileurl;
            }
        }
    }

所以我想要值“return newfileurl;”我的控制器所以如何调用它。所以我可以将字符串保存到我的数据库以获取图像前端

    [HttpPost]
    [ValidateInput(false)]
    public ActionResult NewsCreate(NewsItem ni, HttpPostedFileBase file)
    {
        Guid gi = Guid.NewGuid();
        if (file != null && file.ContentLength > 0)
        {
            CRUDHelper.ImageUpload(file, "newsimage");
        ni.Image = **??????insert solution here??????**;
        db.NewsItems.Add(ni);
        db.SaveChanges();
}

1 个答案:

答案 0 :(得分:0)

CRUDHelper.ImageUpload(file,“newsimage”);已经返回结果,你只需要将它分配给某个东西:ni.Image = CRUDHelper.ImageUpload(file,“newsimage”);

- HimBromBeere