码迷,mamicode.com
首页 > Web开发 > 详细

文件上传

时间:2018-03-22 17:37:05      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:icon   localhost   选择   map   server   proc   src   for   tac   

前端:

<!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:\Users\Jone-pc\Desktop\QQ图片20170705090821.png";//System.Web.Hosting.HostingEnvironment.MapPath(@"C:\Users\Jone-pc\Desktop\QQ图片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") };
        }

  

 

文件上传

标签:icon   localhost   选择   map   server   proc   src   for   tac   

原文地址:https://www.cnblogs.com/liuqiyun/p/8624388.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!