本文转自:http://www.ironspeed.com/articles/Maintain%20File%20Upload%20Control/Article.aspx

Introduction

For security reasons, the File Upload control does not save the posted file name in its View State, so the file is lost on postback.  This is not a bug; it was designed this way so the file cannot be hijacked.  Even Iron Speed’s technical support application has this behavior (compare Fig. 1 and Fig. 2).  For most programmers, the issue is not a big problem.  People with less programming background, however, may become annoyed if their input data gets lost again and again.  During the development of one of my projects, I received so many complaints about the issue that I had to find a solution.

Figure 1. File Upload control with a posted file.

Figure 2.  The posted file is lost on postback after "Add Attachment" is clicked.

Solution

I borrowed my idea for a solution from Google Mail (Gmail).  Gmail allows an email to have multiple files attached.  When you attach more than one file, the previously posted files are shown as text links (Fig. 3).  This can also be accomplished in Iron Speed Designer.

Although the File Upload control cannot save the posted file in its View State, the file can be saved in a session variable for later use.  Its name can be displayed in a Literal control.  Here is the design.

  1. Hide a Literal control behind the File Upload control.
  2. On postback, if the File Upload control contains a file, set the file name to the Literal control. Show the Literal control, and hide the File Upload control.
  3. Save the posted file to a session variable, since it will be needed when the record is saved.

Figure 3.  Gmail's work-around for multiple attachments.

Implementation

Step 1: Add a Literal control to TableControlRow Drag and drop a Literal control (non data-bound) alongside the File Upload control (Fig. 4).  Name it "FilePath".  Note the hidden control "ATCH_FILENM" stores the file name to the database, and the FileDeleteButton. The FileDeleteButton removes the posted file and cancels its upload.

Figure 4.  Add a Literal control alongside the File Upload control.

Step 2: Add a PreRender event handler to switch the visibilities of the controls In the MyTableControlRow class (in file: ...\<App Name>\App_Code\MyFolder\MyPage.Controls.cs or .vb), insert the following code.

C#:

public MyTableControlRow(){     PreRender += new EventHandler(MyTableControlRow_PreRender); }

private void MyTableControlRow_PreRender(object sender, EventArgs e){     if(ATCH_FILE.PostedFile != null && ATCH_FILE.PostedFile.FileName.Length > 0){         // Save PostedFile to a session variable         Page.Session[FilePath.ClientID] = ATCH_FILE.PostedFile;

// Also set filename to ATCH_FILENM         string fullPath = ATCH_FILE.PostedFile.FileName;         int LastIndex = fullPath.LastIndexOf("\\");         ATCH_FILENM.Text = fullPath.Substring((LastIndex + 1));     }

// Show Literal if PostedFile is in the session variable.     if(Page.Session[FilePath.ClientID] != null) {         FilePath.Text = ((HttpPostedFile)Page.Session[FilePath.ClientID]).FileName;         FilePath.Visible = true;         ATCH_FILE.Visible = false;     }else{ // Otherwise, show the FileUpload         FilePath.Visible = false;         ATCH_FILE.Visible = true;     } }

Visual Basic .NET:

Public Sub New()     AddHandler PreRender, AddressOf MyTableControlRow_PreRender End Sub

Private Sub MyTableControlRow_PreRender(ByVal sender As Object, _     ByVal e As EventArgs)     If Not ATCH_FILE.PostedFile Is Not Nothing AndAlso _         ATCH_FILE.PostedFile.FileName.Length > 0 Then         ‘ Save PostedFile to a session variable         Page.Session(FilePath.ClientID) = ATCH_FILE.PostedFile

‘ Also set filename to ATCH_FILENM         Dim fullPath As String = ATCH_FILE.PostedFile.FileName         Dim LastIndex As Integer = fullPath.LastIndexOf("\\")         ATCH_FILENM.Text = fullPath.Substring((LastIndex + 1))     End If

‘ Show Literal if PostedFile is in the session variable.     If Not Page.Session(FilePath.ClientID) Is Not Nothing then         FilePath.Text = _             (DirectCast(Page.Session(FilePath.ClientID), HttpPostedFile)).FileName         FilePath.Visible = True         ATCH_FILE.Visible = False     Else         ‘ Otherwise, show the FileUpload         FilePath.Visible = False         ATCH_FILE.Visible = True     End If End Sub

Step 3: Override FileDeleteButton_Click event handler While still in the MyTableControlRow class, add the following code to remove the posted file from the session if the user discards the file.

C#:

public override void FileDeleteButton_Click(object sender, ImageClickEventArgs args){     base.FileDeleteButton_Click(sender, args);     this.Visible = false;     this.Page.Session.Remove(FilePath.ClientID); }

Visual Basic .NET:

Public Overloads Overrides Sub FileDeleteButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)     MyBase.FileDeleteButton_Click(sender, args)     Me.Visible = False     Me.Page.Session.Remove(FilePath.ClientID) End Sub

Step 4: Override GetUIData() for uploading the file Again in the MyTableControlRow class, insert the following code.

C#:

public override void GetUIData(){     HttpPostedFile file = null;     if (ATCH_FILE.PostedFile != null &&         ATCH_FILE.PostedFile.FileName.Length > 0 &&         ATCH_FILE.PostedFile.ContentLength > 0)         file = ATCH_FILE.PostedFile;     else         file = Page.Session[FilePath.ClientID] as HttpPostedFile;

if(file != null){         DataSource.Parse(MiscUtils.GetFileContent(file), MyTable.ATCH_FILE);         DataSource.Parse(HttpUtility.HtmlDecode(ATCH_FILENM.Text),           MyTable.ATCH_FILENM);     } }

Visual Basic .NET:

Public Overloads Overrides Sub GetUIData()     Dim file As HttpPostedFile = Nothing     If Not ATCH_FILE.PostedFile Is Not Nothing AndAlso _         ATCH_FILE.PostedFile.FileName.Length > 0 AndAlso _         ATCH_FILE.PostedFile.ContentLength > 0 Then         file = ATCH_FILE.PostedFile     Else         file = TryCast(Page.Session(FilePath.ClientID), HttpPostedFile)     End If

If Not file is Not Nothing Then         DataSource.Parse(MiscUtils.GetFileContent(file), MyTable.ATCH_FILE)         DataSource.Parse(HttpUtility.HtmlDecode(ATCH_FILENM.Text), _           MyTable.ATCH_FILENM)     End If End Sub

Step 5: Rebuild and run Here is what it looks like (Fig. 5).

Figure 5. Upload multiple files in Iron Speed Designer generated app.

Conclusion

Although the File Upload control cannot save the posted file in its View State, the file can be saved in a session variable for later use.  Its name can be displayed in a Literal control.

About the Author

Jing Ding has a PhD in Computer Engineering, Bioinformatics and Computational Biology, and an M.S. in Toxicology from Iowa State University. He received his B.S. in biophysics from Fundan University in Shanghai, China. He is a self-taught programmer who "played" with assembly, C and C++ in the 1990s. He took a break from programming from 1997 to 2000. When he picked it up again in 2001, he worked with Java. Jing began working with C# and .NET in 2006. 
   
 

[转]Maintain File Upload Control on Postbacks的更多相关文章

  1. jQuery File Upload 单页面多实例的实现

    jQuery File Upload 的 GitHub 地址:https://github.com/blueimp/jQuery-File-Upload 插件描述:jQuery File Upload ...

  2. jQuery File Upload done函数没有返回

    最近在使用jQuery File Upload 上传图片时发现一个问题,发现done函数没有callback,经过一番折腾,找到问题原因,是由于dataType: ‘json’造成的,改为autoUp ...

  3. kindeditor多图片上传找不到action原来是private File upload成员变量惹得祸

    kindeditor多图片上传找不到action原来是private File upload成员变量惹得祸

  4. 【转发】Html5 File Upload with Progress

    Html5 File Upload with Progress               Posted by Shiv Kumar on 25th September, 2010Senior Sof ...

  5. 用jQuery File Upload做的上传控件demo,支持同页面多个上传按钮

    需求 有这么一个需求,一个form有多个文件要上传,但又不是传统的图片批量上传那种,是类似下图这种需求,一开始是用的swfupload做的上传,但是问题是如果有多个按钮的话,就要写很多重复的代码,于为 ...

  6. jquery file upload 文件上传插件

    1. jquery file upload 下载 jquery file upload Demo 地址:https://blueimp.github.io/jQuery-File-Upload/ jq ...

  7. jQuery File Upload跨域上传

    最近在做一个一手粮互联网项目,方案为前后端分离,自己负责前端框架,采用了Requirejs+avalonjs+jquery三个框架完成. 前后端通过跨域实现接口调用,中间也发现了不少问题,尤其是在富文 ...

  8. 《Play for Java》学习笔记(六)文件上传file upload

    一. Play中标准方法 使用表单form和multipart/form-data的content-type类型. 1.Form @form(action = routes.Application.u ...

  9. jquery ajax发送delete(use in jquery file upload delete file)

    环境: jQuery file upload HTML example code <div class="pic-preview"> <div class=&qu ...

随机推荐

  1. work4

    任务概述 给出多条英文单词,找出一个包含所有单词的填字阵.并且对于该方阵有一定特殊要求: a)      Stage 1 Every phrase in the input file is cover ...

  2. 提高iOS开发效率的方法和工具

    http://www.cocoachina.com/ios/20150717/12626.html 介绍 这篇文章主要是介绍一下我在iOS开发中使用到的一些可以提升开发效率的方法和工具. IDE 首先 ...

  3. POJ 2762 Going from u to v or from v to u? (强连通分量缩点+拓扑排序)

    题目链接:http://poj.org/problem?id=2762 题意是 有t组样例,n个点m条有向边,取任意两个点u和v,问u能不能到v 或者v能不能到u,要是可以就输出Yes,否则输出No. ...

  4. UVa 1640 The Counting Problem (数学,区间计数)

    题意:给定两个数m, n,求从 m 到 n 中0-9数字各出现了多少次. 析:看起来挺简单的,其实并不好做,因为有容易想乱了.主要思路应该是这样的,分区间计数,先从个位进行计,一步一步的计算过来.都从 ...

  5. 创建类模式(零):简单/静态工厂(Static Factory)

    定义 简单工厂模式属于创建型模式,但不属于23种GOF设计模式之一,这也是为什么该模式标记为零的原因.简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例.简单工厂模式是工厂模式家族中最简单实用的 ...

  6. WinDbg x 64 使用 SOS: 无法找到运行时 DLL (clr.dll)

     http://www.datazx.cn/Forums/en-US/59aa78c9-dc05-43c8-9efe-e7b132056afc/action?threadDisplayName=win ...

  7. JS 命名空间 实现方式 收集

    一. 对象注册式 // 声明一个全局对象Namespace,用来注册命名空间Namespace = new Object(); // 全局对象仅仅存在register函数,参数为名称空间全路径,如&q ...

  8. 使用ASP.NET 构建 Web 应用程序快速入门-8小时的免费培训视频

    - Scott Hanselman的中文博客[转载] [原文发表地址] Building Web Apps with ASP.NET Jump Start - 8 Hours of FREE Trai ...

  9. php-fpm 启动和关闭

    php-fpm -c /data/tools/repository/php-5.3.10/etc/php.ini -y /data/tools/repository/php-5.3.10/etc/ph ...

  10. Python写的东西在CMD下打印中文

    以前遇到的问题是在IDLE中可以print出中文,在cmd却是乱码. 后来想明白,IDLE中默认编码是unicode,而cmd中是ANSI,即cp963,即GBK 所以这样就能输出中文了: s = “ ...