Uploading File using Ajax and receiving binary data in Asp.net (C#)[转]

基础知识,可由此衍生。原文:http://uniapple.net/blog/?p=2050

In this post, I will show you how to upload a file using Ajax (Asynchronous JavaScript and XML) and receive the binary data in Asp.net C#. And it is ultra simple!

1. HTML

<input id="bannerImage" name="bannerImage" type="file"><input onclick="javascript:uploadfile()" type="button" value="upload">

2. JS

function uploadfile(){
    var bannerImage = $("#bannerImage").val();

    if (bannerImage) {
            var file = document.getElementById('bannerImage').files[0];
            var formData = new FormData();
            formData.append(file.name, file);

            var xhr = new XMLHttpRequest();
            var url = "/Category/UpdateBannerImage";
            xhr.open('POST', url, true);
            xhr.onload = function (e) {
                var response = $.parseJSON(e.target.response);
                console.log(response.fileName);
            };

           xhr.send(formData);  // multipart/form-data

    }
}

(Sending Binary Data)

3. C#, Receiving binary data

public JsonResult UpdateBannerImage()
{
    HttpPostedFileBase bannerImage = Request.Files[0] as HttpPostedFileBase;
    if (bannerImage != null && bannerImage.ContentLength > 0)
    {
	var fileName = Path.GetFileName(bannerImage.FileName);
	fileName = Regex.Replace(fileName, @"\s|\$|\#\%", "");
	var path = Path.Combine(Server.MapPath("~/images/category_banners"), fileName);
	bannerImage.SaveAs(path);

	return Json(new { success = false ,error = false, message = "Image has been updated successfully", fileName = fileName });
    }
    else
    {
	return Json(new { success = true, error = "File is empty" });
    }
}
posted @ 2014-02-16 18:46  $walker  阅读(514)  评论(0编辑  收藏  举报