首页 > 学院 > 开发设计 > 正文

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

2019-11-17 03:21:14
字体:
来源:转载
供稿:网友

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表