• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
[书籍]用UWP复习《C#并发编程经典实例》发布时间:2022-07-14
下一篇:
语音合成与识别技术在C#中的应用2发布时间:2022-07-14
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap