C# 用原生JS进行文件的上传

1.此文章是用原生JS来进行文件的上传,有两个版本,一个不用ajax,一个用ajax。

1)非AJAX

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <meta charset="utf-8" />
</head>
<body>

<form id="upload-form" action="Template/UploadBusinessImage" method="post" enctype="multipart/form-data">
    <input type="file" id="upload" name="ProductImage"/> <br/>
    <input type="submit" value="上传"/>
</form>

</body>
</html>

 

2)AJAX

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <meta charset="utf-8"/>
    <script>
        /*原生JS版*/
        function updateFile() {
             /* FormData 是表单数据类 */
             var fd = new FormData();
             var ajax = new XMLHttpRequest();
             fd.append("upload", 1);
             /* 把文件添加到表单里 */
             fd.append("ProductImage", document.getElementById("upfile").files[0]);
             ajax.open("post", "Template/UploadBusinessImage", true);

             ajax.onload = function () {
             console.log(ajax.responseText);
            };
         ajax.send(fd);
        }

    </script>
</head>
<body>
    <p><input type="file" id="upfile"></p>
    <p><input type="button" id="upJS" value="用原生JS上传" onclick="updateFile()"></p>
</body>
</html>

 

2. 后台

        public ActionResult UploadBusinessImage(HttpPostedFileBase ProductImage)
        {

            string error = "";
            try
            {
                //文件上传
                HttpPostedFileBase postFileBase = ProductImage;

                //文件后缀
                string extension = Path.GetExtension(postFileBase.FileName);

                //文件流
                Stream uploadStream = postFileBase.InputStream;

                //把文件写入到本地E盘
                using (var fileStream = System.IO.File.Create("E:\\" + postFileBase.FileName))
                {
                    uploadStream.Seek(0, SeekOrigin.Begin);
                    uploadStream.CopyTo(fileStream);
                }

                return this.Json(error, JsonRequestBehavior.AllowGet);

            }
            catch (Exception e)
            {
                return this.Json(e.Message, JsonRequestBehavior.AllowGet);
            }
        }
posted on 2016-09-05 22:05 alun-chen 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/alunchen/p/5843786.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值