ASP.NET FileUpload上传图片方法并解决上传文件大小

在web.config配置

<system.web>

    <httpRuntime executionTimeout="300" maxRequestLength="204800" useFullyQualifiedRedirectUrl="false"/> 

</system.web> 

 C#

 if (FuPhoto.HasFile)

            {

                string fileContentType = FuPhoto.PostedFile.ContentType;

                if (fileContentType == "image/bmp" || fileContentType == "image/gif" || fileContentType == "image/pjpeg")

                {

                    string name = FuPhoto.PostedFile.FileName;                  // 客户端文件路径


                    FileInfo file = new FileInfo(name);

                    // 缩略图文件名称

                    string fileName_s = DateTime.Now.ToString("yyyyMMddHHmmssS") + file.Name;

                    // 服务器端文件路径

                    string webFilePath_s = Server.MapPath("../UploadBlogPhoto/" + userID + "/" + fileName_s);

                    string strCreatPath = "../UploadBlogPhoto/" + userID;


                    if (!File.Exists(webFilePath_s))

                    {

                        try

                        {

                            if (FuPhoto.PostedFile.ContentLength > 2048000)

                            {

                                Jscript.Alert("提示:上传图片大小不能超过2048K");

                                // Response.Write("<script language='JavaScript'>alert('上传图片大小不能超过2048K'):history.go(-1);</script>");

                                return;

                            }

                            if (Directory.Exists(Server.MapPath(strCreatPath)) == false)//如果不存在就创建file文件夹

                            {

                                Directory.CreateDirectory(Server.MapPath(strCreatPath));

                            }

                            FuPhoto.SaveAs(webFilePath_s);  // 使用 SaveAs 方法保存文件

          //model PiUrl属性字段 

                            bumodel.PicUrl = "/UploadBlogPhoto/" + userID + "/" + fileName_s;//压缩过的图片

          //保存方法

                            buBll.Add(bumodel);//添加相片


                            Response.Write("<script language='JavaScript'>alert('添加相片成功');window.location='BlogUserPic.aspx?userID=" + userID + "';</script>");

                            Response.End();

                        }

                        catch (Exception ex)

                        {

                            Jscript.Alert("提示:相片上传失败,失败原因:" + ex.Message);

                        }

                    }

                    else

                    {

                        Jscript.Alert("提示:相片已经存在,请重命名后上传");

                    }

                }

                else

                {

                    Jscript.Alert("提示:相片类型不符");

                }

            }


  

posted @ 2010-05-26 17:44  TC-MrLee  阅读(2842)  评论(2编辑  收藏  举报