编程开发 > ASP > 文章内容

FileUpload上传多文件出现错误的解决方法(四)

2010-10-25编辑:dan
C# 代码
using 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), "", @"<script>alert('总上传的文件超过了大小设置  1024 * 1024 !')</script>");
                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), "", @"<script>alert('不能添加已经添加过的文件!')</script>");
                    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), "", @"<script>alert('上传成功!')</script>");
    }

    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);
                }
            }
        }
    }
}
FileUpload上传多文件出现错误的解决方法(三)

热点推荐

登录注册
触屏版电脑版网站地图