2010-09-07 5 views
1

Comment créer l'environnement pour sélectionner le fichier image et le télécharger dans asp.net MVC 2? Quel code dois-je écrire pour ça?Télécharger une image/un fichier dans asp.net MVC 2

qui scenariois mieux sur:

image du magasin dans la base de données ou de conserver une copie de l'image dans le système de fichiers au domaine d'application et de maintenir son chemin dans DB? quel code doit écrire dans asp.net MVC 2 pour le scénario préféré?

Répondre

1

Code Html

file to upload: <input type="file" name="Photo" id="Photo" /> 

C#

public ActionResult Imageupload(MyObject myObject) 
     { 
      //PhotoForSingleItem is just a class that has properties 
      // Name and Alternate text. I use strongly typed Views and Actions 
      // because I'm not a fan of using string to get the posted data from the 
      // FormCollection. That just seems ugly and unreliable to me. 

      //PhotoViewImage is just a Entity framework class that has 
      // String Name, String AlternateText, Byte[] ActualImage, 
      // and String ContentType 

      HttpPostedFileBase file = Request.Files["Photo"]; 
      //newImage.Name = photo.Name; 
      // newImage.Alt = photo.AlternateText; 

      //Here's where the ContentType column comes in handy. By saving 
      // this to the database, it makes it infinitely easier to get it back 
      // later when trying to show the image. 
      //patient.photo = file.ContentType; 

      Int32 length = file.ContentLength; 
      //This may seem odd, but the fun part is that if 
      // I didn't have a temp image to read into, I would 
      // get memory issues for some reason. Something to do 
      // with reading straight into the object's ActualImage property. 

      try 
      { 
       if (length != 0) 
       { 
        if ((file.ContentType == "image/pjpeg") || (file.ContentType == "image/gif") || (file.ContentType == "image/x-png")) 
        { 
         byte[] tempImage = new byte[length]; 


         file.InputStream.Read(tempImage, 0, length); 




         localRepository.SaveOrUpdate(myObject);// you can insert through sql commands. 
} 
catch(Exception ex){ 

} 
     return View() 
}