FileUpload上傳多檔案時出現“無法訪問已關閉的檔案”錯誤的解決方法

孟子E章發表於2009-12-30

在使用 public static ArrayList files 變數儲存臨時上傳的檔案時,當檔案比較大時,會出現“無法訪問已關閉的檔案”錯誤,網上也有很多這樣的問題,但都沒有解決辦法。在配置檔案中增加

XML/XHTML 程式碼
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --&gt<httpRuntime executionTimeout="90" maxRequestLength="2097151" useFullyQualifiedRedirectUrl="false" requestLengthDiskThreshold="8192"/>

(屬性“maxRequestLength”值必須在 0-2097151 範圍內。)一行之後,可以解決部分問題,但也不能徹底解決。出現這樣的問題的程式碼是這樣寫的: 

ASPX 程式碼
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --&gt@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="admin_Default3" %>
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    
<title>title>
head>
<body>
    
<form. id="form1" runat="server">
    
<div>
        
<table>
            
<tr>
                
<td align="right">
                    本地檔案:
                
td>
                
<td>
                    
<asp:FileUpload ID="fupFile" runat="server" CssClass="btn" Width="247px" Height="20px"
                        onkeydown
="event.returnValue=false;" onpaste="return false" />
                
td>
            
tr>
            
<tr>
                
<td align="right">
                    檔案列表:
                
td>
                
<td valign="top">
                    
<asp:ListBox ID="lbxFile" runat="server" Height="145px" Width="245px" CssClass="txt">
                    
asp:ListBox>
                
td>
            
tr>
            
<tr>
                
<td colspan="5">
                    
<asp:Button ID="btnAdd" runat="server" Text="新增" OnClick="btnAdd_Click" />  
                    
<asp:Button ID="btnPost" runat="server" Text="上傳" OnClick="btnPost_Click" />
                
td>
            
tr>
        
table>
    
div>
    
form>
body>
html>
C# 程式碼
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --&gtusing System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Collections;
using System.IO;

public partial class admin_Default3 : System.Web.UI.Page
{
    
public static ArrayList files = new ArrayList();
    
protected void btnAdd_Click(object sender, EventArgs e)
    {
        
if (fupFile.HasFile)
        {

            ListItem item
= new ListItem();
            item.Value
= item.Text = fupFile.PostedFile.FileName;
            
if (!lbxFile.Items.Contains(item))
            {
                lbxFile.Items.Add(item);
                files.Add(fupFile);
            }
            
else
                Page.ClientScript.RegisterClientScriptBlock(
typeof(string), "", @"
alert('不能新增已經新增過的檔案!')
");
        }
    }
    
protected void btnPost_Click(object sender, EventArgs e)
    {
        
if (files.Count > 0)
        {
            
if (!Directory.Exists(MapPath("../bodyissue/temp")))
                Directory.CreateDirectory(MapPath(
"../bodyissue/temp"));


            
foreach (FileUpload fup in files)
            {
                
if (fup.HasFile)

                    fup.SaveAs(MapPath(
"../bodyissue/temp") + "/" + fup.FileName);//無法訪問已關閉的檔案

            }
            Page.ClientScript.RegisterClientScriptBlock(
typeof(string), "", @"
alert('上傳成功!')
");


        }
    }
}

要實現類似的功能,其實完全沒有必要使用 static 變數,使用 static 變數,也會導致一些問題,因為 .NET 中 static 變數是所有執行緒共同使用的。下面的這個方法的程式碼,就解決這個問題。

ASPX 程式碼
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --&gt@ Page Language="C#" AutoEventWireup="true" CodeFile="MultiFileUpload.aspx.cs"
    Inherits
="MultiFileUplaod" %>
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    
<title>title>
head>
<body>
    
<form. id="form1" runat="server">
    
<asp:HiddenField ID="allFileSize" runat="server" Value="0" />
    
<table>
        
<tr>
            
<td align="right">
                本地檔案:
            
td>
            
<td>
                
<asp:FileUpload ID="FileUpload1" runat="server" />
            
td>
        
tr>
        
<tr>
            
<td align="right">
                檔案列表:
            
td>
            
<td>
                
<asp:ListBox ID="lbxFile" runat="server" Height="145px" Width="245px" CssClass="txt">
                
asp:ListBox>
            
td>
        
tr>
        
<tr>
            
<td colspan="2" style="text-align: center">
                
<asp:Button ID="btnAdd" runat="server" Text="新增檔案" OnClick="btnAdd_Click" />  
                
<asp:Button ID="btnDelete" runat="server" Text="刪除檔案" OnClick="btnDelete_Click" />  
                
<asp:Button ID="btnPost" runat="server" Text="完成上傳" OnClick="btnPost_Click" />
            
td>
        
tr>
    
table>
    
form>
body>
html>

 

C# 程式碼
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --&gtusing System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.IO;

public partial class MultiFileUplaod : System.Web.UI.Page
{
    
private String folder;
    
protected void Page_Load(object sender, EventArgs e)
    {
        folder
=  Server.MapPath("~/temp");
        
if (!Directory.Exists(folder))
            Directory.CreateDirectory(folder);
    }
    
protected void btnAdd_Click(object sender, EventArgs e)
    {
        
if (FileUpload1.HasFile)
        {
            String newFileName
= folder + "/" + Guid.NewGuid().ToString() + Path.GetExtension(FileUpload1.FileName);
            
int totalFileSize = Int32.Parse(allFileSize.Value);
            
int fileSize = FileUpload1.PostedFile.ContentLength;      
            
//此處也可以限制單個檔案的大小
            if (totalFileSize + fileSize > 1024 * 1024)
            {
                Page.ClientScript.RegisterClientScriptBlock(
typeof(string), "", @"
alert('總上傳的檔案超過了大小設定&nbsp;&nbsp;1024 * 1024 !')
");
                
return;
            }            
            FileUpload1.SaveAs(newFileName);
            ListItem item
= new ListItem();
            item.Text
= FileUpload1.FileName;
            item.Value
= newFileName;
            
for (int i = 0; i < lbxFile.Items.Count; i++)
            {
                
if (lbxFile.Items[i].Text.Equals(FileUpload1.FileName, StringComparison.InvariantCultureIgnoreCase))
                {
                    Page.ClientScript.RegisterClientScriptBlock(
typeof(string), "", @"
alert('不能新增已經新增過的檔案!')
");
                    
return;
                }
            }
            totalFileSize
+= fileSize;
            allFileSize.Value
= totalFileSize.ToString();
            lbxFile.Items.Add(item);
        }
    }
    
protected void btnPost_Click(object sender, EventArgs e)
    {
        
//對上傳的檔案進行進一步處理,或者退出彈出視窗等操作
        for (int i = lbxFile.Items.Count - 1; i > -1; i--)
        {
            lbxFile.Items.Remove(lbxFile.Items[i]);
        }
        Page.ClientScript.RegisterClientScriptBlock(
typeof(string), "", @"
alert('上傳成功!')
");
    }

    
protected void btnDelete_Click(object sender, EventArgs e)
    {
        
for (int i = lbxFile.Items.Count - 1; i > -1; i--)
        {
            
if (lbxFile.Items[i].Selected)
            {
                String value
= lbxFile.Items[i].Value;
                lbxFile.Items.Remove(lbxFile.Items[i]);
                
if (File.Exists(value))
                {
                    File.Delete(value);
                }
            }
        }
    }
}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/15723462/viewspace-623941/,如需轉載,請註明出處,否則將追究法律責任。

相關文章