Uploadify in ASP.Net



和分頁類似,文件上傳是web開發標配的技能之一。下面介紹Uploadify的配置和使用。

一、配置

首先到Uploadify官網下載,然后在項目中添加相應引用。前台代碼如下:

1.jquery.js
2.uploadify/jquery.uploadify.js
3.uploadify/uploadify.css

js代碼:

$("#uploadify1").uploadify({
    height: 30,
    width: 120,
    swf: '@Url.Content("~/Content/uploadify/uploadify.swf")',
    uploader: '@Url.Content("~/Home/Upload")',
    'auto': true,
    'buttonText': '上傳圖片',
    'multi': false,
    'sizeLimit' : 2*1024*1024,
    'formData': { 'submitType': 'image', 'studentId':studentId, 'taskId':taskId },
    'fileTypeDesc': '指定文件',
    'fileTypeExts': '*.jpg; *.jpeg; *.png; *.gif',
    'removeTimeout': 2, //進度條消失秒數
    'onInit': function () { },
    'onSelect': function (fileObj) { //判斷文件大小
        var fileSize = fileObj.size;
        if (fileSize > 2*1024*1024) {
            alert("圖片不得大於2M");
            $('#uploadify1').uploadify('cancel');
            return;
        }
    },
    'onUploadComplete': function (file) {
    },
    'onUploadSuccess': function (file, data, response) { //上傳成功回調方法
        data = JSON.parse(data);
        if(data.IsSuccess == "True" ){
            alert("上傳成功");
        }else{
            alert("上傳失敗");
            return;
        }
    }
});

 

html代碼:

<div id="">
<img width="100px;" height="100px;" id="imgPriview" src="http://images4.c-ctrip.com/target/headphoto/portrait_180_180.jpg"
alt="" />
</div>
<input type="file" name="uploadify" id="uploadify" />
<p>
<a href="javascript:$('#uploadify').uploadify('upload','*');">上傳</a>| <a href="javascript:$('#uploadify').uploadify('cancel')">
取消上傳</a>
</p>

 

點擊上傳以后,會將數據提交到后台,交給uploadHandler.ashx處理。

二、后台

一般處理程序ahsx會處理前台提交過來的數據,把圖片保存到磁盤,然后返回圖片的url給客戶端進行預覽。

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/plain";
    context.Response.Charset = "utf-8";

    HttpPostedFile file = context.Request.Files["Filedata"];

    string uploadPath = context.Request.MapPath("/uploadedFiles/");

    string fileName = file.FileName;
    string imgUrl = "http://" + context.Request.Url.Authority + "/uploadedFiles/" + fileName;

    if (file != null)
    {
        if (!Directory.Exists(uploadPath))
        {
            Directory.CreateDirectory(uploadPath);
        }

        file.SaveAs(uploadPath + fileName);
                
        context.Response.Write(imgUrl);
    }
    else
    {
        context.Response.Write("0");
    }

}

 

一個簡單的demo示范如何配置和使用Uploadify,由於Uploadify是基於Flash上傳的,有一個已知的bug是上傳時會丟失sessionId,進而服務端也拿不到cookie, 好在可以通過手動添加sessionId解決。

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM