Thursday, May 13, 2010

asp.net(c#) upload file by ajax

ก่อนอื่นให้ไปโหลดไลบรารีตัวนี้มาก่อนนะครับ valums.com/ajax-upload/
copy code ส่วนนี้ไปว่างระหว่าง
//
$(document).ready(function(){
var button = $('#upload_button'), interval;
new AjaxUpload(button, {
action: 'UploadHandler.ashx',
name: 'myfile',
responseType: 'json',
onSubmit : function(file, ext){
//if (! (ext && /^(mp3|wma|wmv|mp4|mpeg|dat)$/i.test(ext))){
// extension is not allowed
//alert('Error: invalid file extension');
// cancel upload
//return false;
//}
// change button text, when user selects file
button.text('Uploading');
// If you want to allow uploading only 1 file at time,
// you can disable upload button
this.disable();
// Uploding -> Uploading. -> Uploading...
interval = window.setInterval(function(){
var text = button.text();
if (text.length <>
button.text(text + '.');
} else {
button.text('Uploading');
}
}, 200);
},
onComplete: function(file, response){
button.text('Upload');
window.clearInterval(interval);
// enable upload button
this.enable();

// add file to the list
if(response.Status=='success'){
$('
  • ').appendTo('#result').html($("Delete"));
    }else{
    $('#result').append('
  • Fail to upload!
  • ');
    }
    }
    });
    });
    //Delete file
    function FileDelete(sender,path){
    var currentDate = new Date();
    var q = "q="+path+"&seek="+currentDate.getMilliseconds();
    var response = confirm("Are you sure?");
    if(response){
    $.ajax({
    dataType : "json",
    url: "FileDeleteHandler.ashx",
    data: q,
    success: function(msg){
    if(msg.status == "success"){
    $(sender).parents('li:eq(0)').hide();
    }else{
    alert('Error can not delete!');
    }
    },
    error : function(msg){
    alert('Error can not delete!');
    }
    });
    }
    return false;
    }
    //]]>

    ส่วนในform
    begin div id="upload_button"
    Upload
    end div
    ul
    id="result" style="list-style-type: none">
    ul

          หลังจากนั้นให้สร้าง GenericHandler ขึ้นมาครับ
          แล้วโค้ดในมธอด ProcessRequest เป็นเเบบนี้ครับ
          public void ProcessRequest(HttpContext context)
          {

          string strFileName = System.IO.Path.GetFileName(context.Request.Files[0].FileName);
          string strSaveLocation = context.Server.MapPath("ContentImage") + "" + strFileName;
          context.Request.Files[0].SaveAs(strSaveLocation);
          }

          No comments: