2016-04-28 83 views
0
public ActionResult ChangeAvatar(CustomerModel customerModel) 
{ 
    string CustomerID = ""; 
    if (Session["RoleID"] != null) 
    {     
      CustomerID = Request.Form["CustomerID"];        

     //string CustomerID = Request.Form["Customer.CustomerID"]; 
     if (CustomerID != null) 
     { 
      if (Request.Files.Count > 0) 
      { 
       var file = Request.Files[0]; 
       if (file != null && file.ContentLength > 0) 
       { 
        //var fileName = Path.GetFileName(file.FileName);       
        var fileExtension = Path.GetExtension(file.FileName); 
        var allowedExtensions = new[] { ".bmp", ".png", ".jpg", "jpeg", ".gif" }; 
        if (allowedExtensions.Contains(fileExtension)) 
        { 
         //Delete files 
         var pathD = Server.MapPath("~/Avatar/1"); 
         var images = Directory.GetFiles(pathD, CustomerID + ".*"); 
         for (int i = 0; i < images.Length; i++) 
          System.IO.File.Delete(Server.MapPath(("~/Avatar/1/") + Path.GetFileName(images[i]))); 

         //Up files 
         var fileName = CustomerID + fileExtension; 
         var path = Path.Combine(Server.MapPath("~/Avatar/1/"), fileName); 


         file.SaveAs(path); 

         //Session["Avatar"] = fileName; 
        } 
       } 
      } 
     } 
    } 
} 

回答

0

檢查,並相應地改變下面的代碼可以幫助你;)

System.Drawing.Image imageToBeResized = System.Drawing.Image.FromStream(path.PostedFile.InputStream); 
       int imageHeight = imageToBeResized.Height; 
       int imageWidth = imageToBeResized.Width; 
       int maxHeight = 400; 
       int maxWidth = 400; 
       imageHeight = (imageHeight * maxWidth)/imageWidth; 
       imageWidth = maxWidth; 

       if (imageHeight > maxHeight) 
        { 
        imageWidth = (imageWidth * maxHeight)/imageHeight; 
        imageHeight = maxHeight; 
        } 

       Bitmap bitmap = new Bitmap(imageToBeResized, imageWidth, imageHeight); 
       System.IO.MemoryStream stream = new MemoryStream(); 
       bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); 
       stream.Position = 0; 
       byte[] imasave = new byte[stream.Length + 1]; 
       stream.Read(imasave , 0, imasave.Length); 


       file.SaveAs(imasave); 
+0

(path.PostedFile.InputStream)不工作ü可以幫助兄弟 –

+0

你能檢查添加以下代碼 FileUpload MyFile = new FileUpload(); MyFile = Path; System.Drawing.Image imageToBeResized = System.Drawing.Image.FromStream(MyFile.PostedFile.InputStream); –

+0

Myfile = path;給了我錯誤如何將路徑轉換爲myfile –