在ASP.NET 2.0中操作数据之五十四:添加新记录时包(5)

protected void NewCategory_ItemInserting(object sender, DetailsViewInsertEventArgs e) { // Reference the FileUpload controls FileUpload PictureUpload = (FileUpload)NewCategory.FindControl("PictureUpload"); if (PictureUpload.HasFile) { // Make sure that a JPG has been uploaded if (string.Compare(System.IO.Path.GetExtension(PictureUpload.FileName), ".jpg", true) != 0 && string.Compare(System.IO.Path.GetExtension(PictureUpload.FileName), ".jpeg", true) != 0) { UploadWarning.Text = "Only JPG documents may be used for a category's picture."; UploadWarning.Visible = true; e.Cancel = true; return; } } else { // No picture uploaded! UploadWarning.Text = "You must provide a picture for the new category."; UploadWarning.Visible = true; e.Cancel = true; return; } // Set the value of the picture parameter e.Values["picture"] = PictureUpload.FileBytes; // Reference the FileUpload controls FileUpload BrochureUpload = (FileUpload)NewCategory.FindControl("BrochureUpload"); if (BrochureUpload.HasFile) { // Make sure that a PDF has been uploaded if (string.Compare(System.IO.Path.GetExtension(BrochureUpload.FileName), ".pdf", true) != 0) { UploadWarning.Text = "Only PDF documents may be used for a category's brochure."; UploadWarning.Visible = true; e.Cancel = true; return; } const string BrochureDirectory = "~/Brochures/"; string brochurePath = BrochureDirectory + BrochureUpload.FileName; string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(BrochureUpload.FileName); int iteration = 1; while (System.IO.File.Exists(Server.MapPath(brochurePath))) { brochurePath = string.Concat(BrochureDirectory, fileNameWithoutExtension, "-", iteration, ".pdf"); iteration++; } // Save the file to disk and set the value of the brochurePath parameter BrochureUpload.SaveAs(Server.MapPath(brochurePath)); e.Values["brochurePath"] = brochurePath; } }

第8步:更新DisplayCategoryPicture.aspx页面

  让我们花几分钟测试我们在上几步创建的插入界面和ItemInserting事件处理器。在浏览器查看UploadInDetailsView.aspx页面 ,尝试添加一个类,忽略picture或指定一个非JPG的图片或非PDF的小册子。以上任何一种情况下,都会显示一个错误信息,并取消插入操作。

/uploads/allimg/200612/1JF03562_0.gif


图9:当上传的文件不对时将显示一个警告信息

  确认页面要求上传一张图片,且不接受非PDF或非JPG文件。添加一个包含JPG格式图片的新类别,将Brochure列置空,点击Insert按钮后,页面回传,将为Categories表添加一个新记录,同时上传的图片数据直接存储进数据库。GridView控件更新后,将新添加的类显示出来。但是,就像图10所示的那样,类的图片没有正确的显示出来。

/uploads/allimg/200612/1JF11548_0.gif


图10:新类的图片没有显示出来

  图片没有显示出来的原因是因为用来返回特定类的图片的页面DisplayCategoryPicture.aspx被设置为处理带OLE报头的位图。当Picture列的数据被返回到客户端前已经把那78字节的报头剥离掉。而且上传的JPG文件并没有OLE报头,因此,必需的字节已经从图片的二进制数据移除了。

  由于现在表Categories里既有JPG文件又有带OLE报头的位图,我们需要对页面DisplayCategoryPicture.aspx做调整,使它对原来的8个类剥离OLE报头,而不对新添加的类进行剥离。在后面的教程,我们探讨如何更新现有记录的image文件,并将所有以前的类的图片调整为JPG格式。现在,我们在页面DisplayCategoryPicture.aspx 里用下面的代码将原来的8个类的OLE报头剥离。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjwwgz.html