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);
                }
            }
  • 相关阅读:
    内联函数和宏
    python面向对象高级:@property
    python面向对象高级:__slots__
    Python哈希表的例子:dict、set
    python数据结构之哈希表
    python数据结构之队列
    python数据结构之堆栈
    python数据结构之链表
    分治法及其python实现例子
    查找算法:二分法查找及其python实现案例
  • 原文地址:https://www.cnblogs.com/alunchen/p/5843786.html
Copyright © 2011-2022 走看看