记录Harde学习成长生活的点点滴滴.
« »

SwfUpload使用实例

这篇文章是很久以前写的,写的很“雏”,大家见谅~~
大家不妨看看这篇文章:
SwfUpload的实际使用案例[PHP]:http://www.harde.org/blog/archives/1547

因为一个项目需要用到上传,客户要求需要看到上传进度

想想用Flash上传组件是最简单的,去SWFUpload网站看看

版本已经更新到了2.2

简单看了下说明文档,改动不大,就是增加了Flash 10的支持

下载demo看了看,自己试是着写了一个

 

我用C#写的,其他语言都差不多,自己更改吧

新建一个网站,建立JS(用来存放JavaScript脚本)、CSS、Upload(用来存放上传文件)

然后把fileprogress.js handlers.js swfupload.js swfupload.queue.js放入JS文件夹

(挨个文件夹翻翻,我用的是multiinstancedemo里的JS,各个文件夹里除了swfupload.js其他的文件根据需要都是不一样的……我懒得自己写了,(貌似我也不会写)就直接用现成的吧

 

打开Default.aspx

在head里写入下面的代码

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<script type="text/javascript">
	//SWFUpload的属性和方法很多,大家可以看说明文档
 
	function uploadSuccess(file, serverData) {//因为后面一个地方需要到服务器返回的信息,而SwfUpload里我只发现这个方法可以接受到返回信息
	try {//另外说下,只要服务器返回200 SWFUPLOAD才会认为上传成功,因此服务器接收端必须返回点东西才行
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setComplete();
		progress.setStatus("Complete.");
		//--------这一段是我测试用的----------------------------------------------------
		var uploadFiles = document.getElementById("details");
		details.innerHTML="<embed height=45 src='"+serverData+"'></embed>";
		//--------------------------------------------------------------------------------
		progress.toggleCancel(false);
 
	} catch (ex) {
		this.debug(ex);
	}
}
 
		var swfu;
		window.onload = function () {
			swfu = new SWFUpload({
				// Backend Settings
				upload_url: "upload.aspx",
                post_params : {
                    "ASPSESSID" : "<%=Session.SessionID %>"
                },
 
				// 上传文件设置
				file_size_limit : "10 MB",//这里定义上传文件的最大大小0为不限制
				file_types : "*.mp3;*.wma;*.wav;",//这里定义上传文件的格式 *.*为不限制
				file_types_description : "MP3、WMA、WAV 格式文件",//描述  不写的话默认为 "All Files"
				file_upload_limit : "3",    // 最多允许上传的文件数,0为不限制
 
				// Event Handler Settings - these functions as defined in Handlers.js
				//  The handlers are not part of SWFUpload but are part of my website and control how
				//  my website reacts to the SWFUpload events.
				//事件绑定,下面的方法大多是在handlers.js中定义的
				//因为我上面定义了uploadSuccess所以我在handlers.js中删除了uploadSuccess
				file_dialog_start_handler : fileDialogStart,
				file_queued_handler : fileQueued,
				file_queue_error_handler : fileQueueError,
				file_dialog_complete_handler : fileDialogComplete,
				upload_start_handler : uploadStart,
				upload_progress_handler : uploadProgress,
				upload_error_handler : uploadError,
				upload_success_handler : uploadSuccess,
				upload_complete_handler : uploadComplete,
 
				// Button settings
				button_image_url : "images/XPButtonNoText_160x22.png",
				button_placeholder_id : "spanButtonPlaceholder",
				button_width: 160,
				button_height: 22,
				button_text : '<span class="button">选择文件 <span class="buttonSmall">(10 MB Max)</span></span>',
				button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 14pt; } .buttonSmall { font-size: 10pt; }',
				button_text_top_padding: 1,
				button_text_left_padding: 5,
 
				// Flash Settings
				flash_url : "swfupload.swf",	// Relative to this file
 
				custom_settings : {
					progressTarget : "fsUploadProgress",
					cancelButtonId : "btnCancel"
				},
 
				// Debug Settings
				debug: false
			});
		}
	</script>

 

然后在Body中写入

1
2
3
4
5
6
7
8
9
10
<div id="swfu_container" style="margin: 0px 10px">
<div>
<div class="fieldset flash" id="fsUploadProgress">
				<span id="spanButtonPlaceholder"></span>
		    </div>
<div id="divFileProgressContainer" style="height: 75px"></div>
<input id="btnCancel" style="font-size: 8pt; margin-left: 2px; height: 22px" disabled onclick="cancelQueue(swfu);" type="button" value="取消上传" />
		    </div>
<div id="details"></div>
</div>

 

打开Default.aspx.cs

在PageLoad方法中写入

Session.Clear();

ok,主页面完成,下面写接受页面

新建一个Upload.aspx

因为我需要返回歌曲的地址,所以我把页面内容全删除了

只留下

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="upload.aspx.cs" Inherits="upload" %>

然后在Upload.aspx.cs中写入

        if (Request.Files["Filedata"] == null)
        {
            Response.Redirect("Default.aspx");
        }

        Stream stream = null;//真是文件的流
        Stream previewstream = null;//预览文件的流
         BinaryReader br = null;//定义一个二进制读入流
        BinaryWriter bw = null;//定义一个二进制写入流

		HttpPostedFile uploadfile = Request.Files["Filedata"];
        if (uploadfile != null)
        {
            DateTime dt = DateTime.Now;
            String path = dt.ToString("yyyy\\MM\\dd");
            String serverpath = Server.MapPath(".");

//GetNowTimeRan()    是我写的一个生成文件名的方法,这里就不写了,想要看看的可以留下您的Email
            String realFile = serverpath + "\upload\" + path + "\" + GetNowTimeRan() + uploadfile.FileName.Substring(uploadfile.FileName.LastIndexOf("."));
            String tempFileName = GetNowTimeRan() + uploadfile.FileName.Substring(uploadfile.FileName.LastIndexOf("."));
            String previewFile = serverpath + "\preview\" + path + "\" + tempFileName;

            //检查路径是否存在,不存在则创建
            CreateDirectory(serverpath, path);

            stream = uploadfile.InputStream;
            previewstream = File.Create(previewFile);
            br = new BinaryReader(stream);
            bw = new BinaryWriter(previewstream);
            int oldfilecount =Convert.ToInt32(stream.Length);
            int count = 100000;

            if (oldfilecount < count||count<10000)
            {
                count = 1000000;
            }

            if (uploadfile != null && uploadfile.ContentLength > 0)
                {
                //保存真实文件
                uploadfile.SaveAs(realFile);

                //保存预览文件
                for (int j = 0; j < count; j++)//进行循环读取并添加到写入流中
                {
                    bw.Write(br.ReadByte());
                }

            }

            Response.Write("\Desktop1\preview\" + path + "\" + tempFileName);

            bw.Close();
            br.Close();
            stream.Close();
            stream.Dispose();
            previewstream.Close();
            previewstream.Dispose();

        }

OK,搞定,大家可以试着编译运行了。

日志信息 »

该日志于2009-04-30 17:23由 harde 发表在DotNet分类下, 你可以发表评论。除了可以将这个日志以保留源地址及作者的情况下引用到你的网站或博客,还可以通过RSS 2.0订阅这个日志的所有评论。

相关日志 »

11条评论

  1. wsk 说道:

    GetNowTimeRan()
    可不可以把这个方法给我发下
    呵呵,谢谢了

    回复

    harde Reply:

    可以啊

    protected string GetNowTimeRan()
    {
    DateTime Time = DateTime.Now; //获取系统时间
    string Str = Time.Year.ToString();
    if (Time.Month < 10)
    Str += “0″ + Time.Month.ToString();
    else
    Str += Time.Month.ToString();
    if (Time.Day < 10)
    Str += “0″ + Time.Day.ToString();
    else
    Str += Time.Day.ToString();
    if (Time.Hour < 10)
    Str += “0″ + Time.Hour.ToString();
    else
    Str += Time.Hour.ToString();
    if (Time.Minute < 10)
    Str += “0″ + Time.Minute.ToString();
    else
    Str += Time.Minute.ToString();
    if (Time.Second < 10)
    Str += “0″ + Time.Second.ToString();
    else
    Str += Time.Second.ToString();

    if (Time.Millisecond < 100)
    Str += “0″ + Time.Millisecond.ToString();
    else
    if (Time.Millisecond < 10)
    Str += “00″ + Time.Millisecond.ToString();
    else
    Str += Time.Millisecond.ToString();
    //随机数字发生器
    System.Random Random = new Random();
    int _Temp;
    for (int i = 0; i < 3; i++)
    {
    _Temp = Random.Next();
    _Temp = _Temp % 10;
    Str += _Temp.ToString();
    }
    return Str;
    }

    回复

  2. 说道:

    可以将CreateDirectory()方法发给我吗?

    回复

  3. 说道:

    您可以发个完整事例给我吗?

    回复

    harde Reply:

    貌似这个有点困难,年初硬盘挂了,这个项目已经没有了 …不过上面的问题还是可以解决的

    很简单的问题
    就是先检测下目标文件夹是否存在
    不存在就生成

    就这么简单啊

    回复

  4. 说道:

    我按照恩的方法,报错

    回复

  5. 说道:

    报fileDialogStart未定义,但是我导入达js文件啊

    回复

  6. 小魏 说道:

    不错的建议

    回复

  7. zz 说道:

    Microsoft JScript 运行时错误: ‘SWFUpload’ 未定义

    回复

    harde Reply:

    确定引入js文件且无其他JS与其冲突?

    回复

  8. zz 说道:

    这个是什么问题?我用vs2008编的

    回复

发表评论 »

使用新浪微博登陆

返回顶部
分享按钮