zoukankan      html  css  js  c++  java
  • 文件上传

    FormData();支持ie10 ie10+

    前端:

    <!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title></title>
        <meta charset="utf-8" />
        <script type="text/javascript">
    
            $.support.cors = true;
            var ApiUrl = "http://localhost:12745/";
            $(function () {
                $("#upload").click(function () {
                    $("#imgWait").show();
                    var formData = new FormData();
                    formData.append("myfile", document.getElementById("file1").files[0]);
                    $.ajax({
                        url: ApiUrl + "api/FileManage/UploadFile",
                        type: "POST",
                        data: formData,
                        /**
                        *必须false才会自动加上正确的Content-Type
                        */
                        contentType: false,
                        /**
                        * 必须false才会避开jQuery对 formdata 的默认处理
                        * XMLHttpRequest会对 formdata 进行正确的处理
                        */
                        processData: false,
                        success: function (data) {
                            if (data.status == "true") {
                                alert("上传成功!");
                            }
                            if (data.status == "error") {
                                alert(data.msg);
                            }
                            $("#imgWait").hide();
                        },
                        error: function () {
                            alert("上传失败!");
                            $("#imgWait").hide();
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
        选择文件:<input type="file" id="file1" /><br />
        <input type="button" id="upload" value="上传" />
        <img src="wait.gif" style="display:none" id="imgWait" />
    </body>
    </html> 

     

    后端:

    /// <summary>
            /// 文件上传
            /// </summary>
            /// <returns></returns>
            [HttpPost]
            public HttpResponseMessage UploadFile()
            {
    
                
                HttpResponseMessage result = null;
                var httpRequest = System.Web.HttpContext.Current.Request;
                if (httpRequest.Files.Count > 0)
                {
                    try
                    {
                        string url = string.Empty;
                        foreach (string file in httpRequest.Files)
                        {
    
                            var postedFile = httpRequest.Files[file];
                            var filePath = System.Web.HttpContext.Current.Server.MapPath("~/Files/");
                            if (!Directory.Exists(filePath))
                            {
                                Directory.CreateDirectory(filePath);
                            }
                            postedFile.SaveAs(filePath + postedFile.FileName);
                            url += "Files/" + postedFile.FileName + ",";
                        }
    
                        result = Request.CreateResponse(HttpStatusCode.OK, url.Substring(0, url.Length - 1));
    
                    }
                    catch (Exception ex)
                    {
                        result = Request.CreateResponse(HttpStatusCode.OK, "error:" + ex.Message);
                    }
    
                }
                else
                {
                    result = Request.CreateResponse(HttpStatusCode.OK, "0");
                }
                return result;
            }
            /// <summary>
            /// 根据ID 下载文件
            /// </summary>
            /// <returns></returns>
            [HttpGet]
            public HttpResponseMessage DownLoadFile(Guid id)
            {
    
                try
                {
                    DataTable dt = null; //BLL.Menu.GetModelByID(id);
                    if (dt.Rows.Count>0)
                    {
                        byte[] bytes = dt.Rows[0]["Icon"] as byte[];
                        if (bytes.Length>0)
                        {
                            //InputStream input = new ByteArrayInputStream(bytes);
                        }
                    }
                    var FilePath = @"C:UsersJone-pcDesktopQQ图片20170705090821.png";//System.Web.Hosting.HostingEnvironment.MapPath(@"C:UsersJone-pcDesktopQQ图片20170705090821.png");
                    var stream = new FileStream(FilePath, FileMode.Open);
                    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                    response.Content = new StreamContent(stream);
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    
                    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = "Wep Api Demo File.jpg"
                    };
                    return response;
                }
                catch (Exception ex)
                {
                    return new HttpResponseMessage(HttpStatusCode.NoContent);
                }
    
            }
    
    
            /// <summary>
            /// 将文件上传到指定路径中保存
            /// </summary>
            /// <returns>上传文件结果信息</returns>
            [System.Web.Http.HttpPost]
            //[ValidateInput(false)]
            public HttpResponseMessage PostExcelData()
            {
                string info = string.Empty;
                try
                {
                    //获取客户端上传的文件集合
                    HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
                    //判断是否存在文件
                    if (files.Count > 0)
                    {
                        //获取文件集合中的第一个文件(每次只上传一个文件)
                        HttpPostedFile file = files[0];
                        //定义文件存放的目标路径
                        string targetDir = System.Web.HttpContext.Current.Server.MapPath("~/FileUpLoad/Product");
                        //创建目标路径
                        //ZFiles.CreateDirectory(targetDir);
                        if (!System.IO.Directory.Exists(targetDir))
                        {
                            Directory.CreateDirectory(targetDir);
                        }
                        string fullDir = System.IO.Path.Combine(targetDir + file.FileName);
                        //组合成文件的完整路径
                        //string path = System.IO.Path.Combine(targetDir, System.IO.Path.GetFileName(file.FileName));
                        //保存上传的文件到指定路径中
                        file.SaveAs(fullDir);
                        info = "上传成功";
                    }
                    else
                    {
                        info = "上传失败";
                    }
                }
                catch
                {
                    info = "上传失败";
                }
                return new HttpResponseMessage { Content = new StringContent(info, System.Text.Encoding.UTF8, "text/html") };
            }
    

      

     

     也可使用new ByteArrayContent(File.ReadAllBytes(imageUrl)) 试试

  • 相关阅读:
    开始学习编写用于 Windows SideShow 设备的小工具【转】
    Windows Mobile 6.5 Developer Tool Kit 下载
    Microsoft Security Essentials 微软免费杀毒软件下载
    SQL Server 2008 空间数据存储摘抄(SRID 点 MultiPoint LineString MultiLineString 多边形 MultiPolygon GeometryCollection)
    Vista Sidebar Gadget (侧边栏小工具)开发教程 (2)
    Vista Sidebar Gadget (侧边栏小工具)开发教程 (4)
    负载测试、压力测试和性能测试的异同
    Windows Server 2008 Vista Sidebar Gadget (侧边栏小工具) 入门开发实例
    Silverlight Tools 安装失败 解决办法
    SQL Server 2008 空间数据库 空间索引概念及创建(取自帮助)
  • 原文地址:https://www.cnblogs.com/liuqiyun/p/8624388.html
Copyright © 2011-2022 走看看