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" });
    }
}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。