zoukankan      html  css  js  c++  java
  • 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" });
        }
    }
  • 相关阅读:
    JavaScript OOP 思想
    单页界面和 AJAX 模式
    jQuery 的 ready 函数是如何工作的?
    Dojo系列教程
    谈谈javascript语法里一些难点问题(一)
    2014年总结、2015年的小计划--女生程序员小感想
    Android名词解释
    【JS】defer / async
    关于对defer的理解.
    defer和async的区别
  • 原文地址:https://www.cnblogs.com/walkerwang/p/3551647.html
Copyright © 2011-2022 走看看