zoukankan      html  css  js  c++  java
  • 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);
                }
            }
  • 相关阅读:
    96. 不同的二叉搜索树
    95. 不同的二叉搜索树 II
    94. 二叉树的中序遍历
    93. 复原IP地址
    python-007(用户登录(三次机会重试))
    python-006求1-2+3-4+5.....99的所有数的和
    python006(求1-2+3-4+5.....99的所有数的和)
    python-005(1-100奇数和偶数)
    python-004(while循环)
    python-003(if...elif...else)
  • 原文地址:https://www.cnblogs.com/alunchen/p/5843786.html
Copyright © 2011-2022 走看看