0

Im working in MVC4 visual studio a few time ago. im really new in this and hope anyone can help me.

I have a form in my website with input type="text" and input type="file".

I want to insert a new item in my database with multiple imageuploads.

i try to do to do this in view, controller and model.

I have search something and find a code who help a lot to to the upload of several images.

But what i want is when i click on the button do the upload of all the images and inserto into my table all information from the other fields and the files names of all the images. So i can select in another page all images associated at this id.

Hope someone can help with this.

here is my code:

thanks in advance

View:

@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>
}

Controller:

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

Model:

 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();
            }
        }
}
user2232273
  • 4,898
  • 15
  • 49
  • 75
  • what exactly is your problem? – rajeemcariazo Jul 29 '13 at 15:26
  • 1
    First of all, you shouldn't have that static method in your Model. That should be moved into a Controller. Besides that, what is your problem? Do you get the uploaded files in your Action, but your Model is null? – ataravati Jul 29 '13 at 15:28
  • Upload the images works, all of them are in my folder. My problem is that i cant insert the other information from my form into my table . in my table i want to insert the name, title, and all file names from all the images which the user have uploaded – user2232273 Jul 29 '13 at 15:32
  • `ImageUploaded = filename; <== ERROR HERE ALSO` Well that is because `filename` is a string?! – Belogix Jul 29 '13 at 15:47
  • But, why can't you do that? Is that because they are not posted to your Action? – ataravati Jul 29 '13 at 15:48
  • http://stackoverflow.com/questions/15662252/how-to-upload-display-images-using-asp-net-mvc4-with-entity-framework/15662506#15662506 – Rob G Jul 29 '13 at 15:55
  • @Belogix: yep you are right.. i searching in this moment how can i correct this.... – user2232273 Jul 29 '13 at 15:56
  • @ataravati: what do you mean? – user2232273 Jul 29 '13 at 15:58
  • What you are doing has to be changed dramatically. The saving of the uploaded images has to be done in a Controller, but besides that, you don't explain why you can't insert the other information. Do you get an error message when trying to insert, or do you have a Model Binding issue? – ataravati Jul 29 '13 at 16:03
  • @ataravati: I can´t insert the other information and i don´t know why, because i dont get an error on submit the form.. And Thanks for the help and pacient with me.. but i dont understand very much of mvc 4 in visual studio. – user2232273 Jul 29 '13 at 16:06
  • Well, I recommend that you read some tutorials on MVC first. Here in this post, you can find a solution for what you want to achieve: http://stackoverflow.com/questions/15106190/uploading-files-into-database-with-asp-net-mvc – ataravati Jul 29 '13 at 16:10

1 Answers1

0

First, set a breakpoint inside your POST method in your controller. While debugging let the execution hit this breakpoint and verify the model has all the properties set as you expect. If not, you might have a problem binding the form to your model.

Also, if you are familiar with SQL Profiler you can use this to see if a SQL Insert is happening at all and the values being passed in.

I suggest looking into ways of improving your debugging abilities with your code. Perhaps some additional logging as well.

As for the comments about moving your methods around - research Domain Model pattern/Domain Driven Design. Also look up the Anti-Pattern "Anemic Domain Model" (some frown on this) so you can make your own decision as to where your methods need to go.

0xElGato
  • 353
  • 2
  • 10