无法转换为System.Web.HttpPostedFileBase'到'字符串'

时间:2016-05-02 04:35:44

标签: asp.net drawing

var file = Request.Files[0];
                    //HttpPostedFileBase hpf = 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);

一切正常,但遇到一行问题

                            System.Drawing.Image imageToBeResized = System.Drawing.Image.FromFile(file);
                            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);

                            var newImage = System.Drawing.Image.FromStream(stream);
                            newImage.Save(path);
当我传递文件时,

下面的行给我错误                System.Drawing.Image imageToBeResized = System.Drawing.Image.FromFile(file);

1 个答案:

答案 0 :(得分:0)

System.Drawing.Image.FromFile接受一个字符串参数。

,而不是给它文件变量给出你获得文件的路径,它将起作用。

 System.Drawing.Image.FromFile(Path.GetFileName(file.Filename));
                                  or
   System.Drawing.Image.FromFile(Server.MapPath(Path.GetFileName(file.Filename)));