MVC4上传图像并插入数据库

时间:2013-07-29 15:20:59

标签: c# asp.net asp.net-mvc asp.net-mvc-4 file-upload

我刚刚在MVC4视觉工作室工作。我真的很新,希望有人能帮助我。

我的网站上有一个表单,输入类型=“text”,输入类型=“文件”。

我想在我的数据库中插入一个包含多个imageuploads的新项目。

我尝试在视图,控制器和模型中执行此操作。

我搜索了一些内容并找到了一些代码,这些代码可以帮助您上传多张图片。

但我想要的是当我点击按钮时,将所有图像和inserto上传到我的表中,来自其他字段的所有信息和所有图像的文件名。所以我可以在另一个页面中选择与此ID相关联的所有图像。

希望有人可以帮忙解决这个问题。

这是我的代码:

提前致谢

查看:

@using (Html.BeginForm("Uploading", "AdicionarRevista", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

<label for="file">Nome da Empresa:</label>   
<input type="text" name="Name" id="nome" /><br />

<label for="file">Titulo da Revista:</label>       
<input type="text" name="Title" id="titulo" /> <br />

<label for="file">Upload:</label>         
<input type="file" name="ImageUploaded" id="btnUpload" multiple="multiple" accept="image/*"  />    <br />

<button type="submit"  id="Upload">Upload</button>
}

控制器:

  [HttpPost]
        public ActionResult Uploading(ImageModel infouploadimage)
        {
            for (int i = 0; i < Request.Files.Count; i++)
            {
                if (Request.Files[i].ContentLength > 0)
                {
                    HttpPostedFileBase uploadedFile = Request.Files[i];
                    string fileName = Guid.NewGuid().ToString();
                    string serverPath = Server.MapPath("~");
                    string imagesPath = serverPath + "Content\\Images\\";
                    string thumsise = Path.Combine(imagesPath, "Thumb" + fileName);
                    string thumbPath = Path.Combine(imagesPath, "Thu" + fileName);
                    string fullPath = Path.Combine(imagesPath, "Full" + fileName);
                    string Bigpath = Path.Combine(imagesPath, "big" + fileName);
                    string Bigpatha = Path.Combine(imagesPath, "biga" + fileName);
                    string Bigpathb = Path.Combine(imagesPath, "bigb" + fileName);
                    string Bigpathc = Path.Combine(imagesPath, "bigc" + fileName);
                    ImageModel.ResizeAndSave(thumsise, fileName, uploadedFile.InputStream, 80, true);
                    ImageModel.ResizeAndSave(thumbPath, fileName, uploadedFile.InputStream, 100, true);
                    ImageModel.ResizeAndSave(fullPath, fileName,  uploadedFile.InputStream, 500, true);
                    ImageModel.ResizeAndSave(Bigpath, fileName, uploadedFile.InputStream, 200, true);
                    ImageModel.ResizeAndSave(Bigpatha, fileName, uploadedFile.InputStream, 250, true);
                    ImageModel.ResizeAndSave(Bigpathb, fileName, uploadedFile.InputStream, 150, true);
                    ImageModel.ResizeAndSave(Bigpathc, fileName, uploadedFile.InputStream, 50, true);

                }
            }


            return RedirectToAction("Index", "Home");
        }

型号:

 public class ImageModel
    {

        [Required]

        public string Name{ get; set; }
        public string Title{ get; set; }

        public HttpPostedFileWrapper ImageUploaded { get; set; }
        public static void ResizeAndSave(string savePath, string fileName, Stream imageBuffer, int maxSideSize, bool makeItSquare)
        {
            int newWidth;
            int newHeight;
            Image image = Image.FromStream(imageBuffer);
            int oldWidth = image.Width;
            int oldHeight = image.Height;
            Bitmap newImage;
            if (makeItSquare)
            {
                int smallerSide = oldWidth >= oldHeight ? oldHeight : oldWidth;
                double coeficient = maxSideSize / (double)smallerSide;
                newWidth = Convert.ToInt32(coeficient * oldWidth);
                newHeight = Convert.ToInt32(coeficient * oldHeight);
                Bitmap tempImage = new Bitmap(image, newWidth, newHeight);
                int cropX = (newWidth - maxSideSize) / 2;
                int cropY = (newHeight - maxSideSize) / 2;
                newImage = new Bitmap(maxSideSize, maxSideSize);
                Graphics tempGraphic = Graphics.FromImage(newImage);
                tempGraphic.SmoothingMode = SmoothingMode.AntiAlias;
                tempGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                tempGraphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
                tempGraphic.DrawImage(tempImage, new Rectangle(0, 0, maxSideSize, maxSideSize), cropX, cropY, maxSideSize, maxSideSize, GraphicsUnit.Pixel);
            }
            else
            {
                int maxSide = oldWidth >= oldHeight ? oldWidth : oldHeight;

                if (maxSide > maxSideSize)
                {
                    double coeficient = maxSideSize / (double)maxSide;
                    newWidth = Convert.ToInt32(coeficient * oldWidth);
                    newHeight = Convert.ToInt32(coeficient * oldHeight);
                }
                else
                {
                    newWidth = oldWidth;
                    newHeight = oldHeight;
                }
                newImage = new Bitmap(image, newWidth, newHeight);
            }
            newImage.Save(savePath + fileName + ".jpg", ImageFormat.Jpeg);
            //newImage.Save(savePath + fileName + ".jpg", ImageFormat.Jpeg);
            image.Dispose();
            newImage.Dispose();
        }

        public void infouploadimage(string name, string title,string filename)
        {
            Name= name;
            Title= title;
           ImageUploaded = filename; <== ERROR HERE ALSO

            string connection = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

            using (SqlConnection connect = new SqlConnection(connection))
            {
                string query = "Insert Into MYtable(Name, Title, Images) Values(@name, @title, ???)";

                SqlCommand command = new SqlCommand(query, connect);
                command.Parameters.AddWithValue("NomeEmpresa", n_empresa);
                command.Parameters.AddWithValue("Titulo", titulo_revista);
                //command.Parameters.AddWithValue("filename", ImageUploaded);
                connect.Open();
                command.ExecuteNonQuery();
            }
        }
}

1 个答案:

答案 0 :(得分:0)

首先,在控制器的POST方法中设置断点。在调试时让执行命中此断点并验证模型是否按预期设置了所有属性。如果没有,您可能会遇到将表单绑定到模型的问题。

此外,如果您熟悉SQL事件探查器,则可以使用它来查看是否发生了SQL插入以及传入的值。

我建议您研究一下使用代码提高调试能力的方法。也许还有一些额外的日志记录。

关于移动你的方法的评论 - 研究领域模型模式/领域驱动设计。还要查看反模式“贫血领域模型”(有些人不屑一顾),这样你就可以自己决定你的方法需要去哪里。