zoukankan      html  css  js  c++  java
  • c#使用js上传图片

    前几天朋友说用js上传图片过去遇到点问题,于是自己也想写一个demo这里就把自己挖的坑填了。

    话不多说上代码

    前台就一个file控件加按钮

    <!DOCTYPE html>
    <html>
    
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="scripts/jquery-1.9.1.min.js"></script>
    </head>
    
    <body>
        <input type="file" name="file" id="testFile" nultiple="multiple" />
        <input type="button" id="btnSend" value="上传" onclick="UploadFile()" />
    
    
        <script>
            function UploadFile() {
                var formData = new FormData();
                jQuery.support.cors = true;
                var file = $("#testFile")[0].files[0];
                formData.append("file", file);
                $.ajax({
                    type: "post",
                    url: "./api/file/FileByAsyncTask",
                    data: formData,
                    async: false,
                    /**
                       *必须false才会自动加上正确的Content-Type
                    */
                    contentType: false,
                    /**
                       * 必须false才会避开jQuery对 formdata 的默认处理
                       * XMLHttpRequest会对 formdata 进行正确的处理
                    */
                    processData: false,
                    success: function (data) {
                        console.log(data);
                    },
                    error: function (data) {
                        console.log(data.statusText);
                    }
                });
            }
        </script>
    </body>
    </html>

    这里需要注意的就是在发送文件的时候需要使用FormData进行传递

    后台代码(用了三种方式处理)
    public class FileController : ApiController
        {
            TimeSpan tspan = DateTime.Now - new DateTime(1970, 1, 1);
    
            /// <summary>
            /// 图片上传接口
            /// </summary>
            /// <returns></returns>
            [HttpPost]
            public HttpResponseMessage FileUpload()
            {
                if (!Request.Content.IsMimeMultipartContent("form-data"))
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                HttpResponseMessage response = new HttpResponseMessage();
                try
                {
                    HttpPostedFile file = HttpContext.Current.Request.Files["file"];//获取http传输的文件
                    string domainPath = HttpRuntime.AppDomainAppPath.ToString();//物理路径 二选一
                    string serverPath = System.Web.Hosting.HostingEnvironment.MapPath("~/images/img/");//物理路径
                    string ext = Path.GetExtension(file.FileName);//获取扩展名
                    string newName = tspan.TotalMilliseconds + ext;//时间戳+扩展名形成新文件名
    
                    //方式一 直接保存上传文件
                    //FileByHttpPostedFile(file,serverPath,tspan.TotalMilliseconds+ext);
    
                    //方式二 图片流处理
                    //ImageByStream(file, serverPath, newName);
    
                    //方式三 先创建文件在移动到指定目录
    
                    response.Headers.Add("Access-Control-Allow-Origin", "*");
                    response.Headers.Add("Access-Control-Alow-Method", "post");
                    response.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
                    response.Headers.Add("Access-Control-Max", "3600");
                    return response;
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
    
            /// <summary>
            /// 方法一 通过HttpPostedFile保存
            /// </summary>
            /// <param name="file">Http接收到的文件</param>
            /// <param name="savePath">保存地址</param>
            /// <param name="filename">文件名</param>
            public void FileByHttpPostedFile(HttpPostedFile file, string serverPath, string fileName)
            {
                file.SaveAs(serverPath + fileName);
            }
    
            public void ImageByStream(HttpPostedFile file, string serverPath, string fileName)
            {
                using (Image img = Bitmap.FromStream(file.InputStream))
                {
                    img.Save(serverPath + fileName);
                }
            }
    
            /// <summary>
            /// 异步上传
            /// </summary>
            /// <param name="postFile"></param>
            /// <returns></returns>
            [HttpPost]
            public async Task<bool> FileByAsyncTask()
            {
                if (!(HttpContext.Current.Request.Files.Count > 0))//判断是否文件
                    return false;
                HttpPostedFile postFile = HttpContext.Current.Request.Files["file"];//获取文件
                string serverPath = System.Web.Hosting.HostingEnvironment.MapPath("~/images/img/");//获取服务器地址
                var provider = new MultipartFormDataStreamProvider(serverPath);//创建MIME 多部分正文新实例
                IEnumerable<HttpContent> parts = null;
                Task.Factory.StartNew(() =>
                {
                    parts = Request.Content.ReadAsMultipartAsync(provider).Result.Contents;//异步获取多部分正文内容
                },CancellationToken.None,
                TaskCreationOptions.LongRunning,
                TaskScheduler.Default).Wait();
                foreach (var file in provider.FileData)//文件保存
                {
                    FileInfo _fileInfo = new FileInfo(file.LocalFileName);
                    var  fileName = file.Headers.ContentDisposition.FileName.Replace(""","");//从内容读取文件名
                    string _ext = Path.GetExtension(fileName);//content获取文件名是 "header.jpg"   函数识别字符串  header.jpg所以需要去掉双引号
                    string _savePath = Path.Combine(serverPath + tspan.TotalMilliseconds + _ext);
                    _fileInfo.MoveTo(_savePath);
                }
                return true;
            }
        }

    比较菜,希望以后继续努力



  • 相关阅读:
    软件概要设计
    Jmter进行Rabbitmq测试
    分布式锁
    实用异常
    异常集合
    本地Windows环境安装RabbitMQ Server
    MySQL千万级多表关联SQL语句调优
    mysql数据库多表关联查询的慢SQL优化
    rabbitmq详细配置
    Idea连接服务器docker并部署代码到docker实现一键启动
  • 原文地址:https://www.cnblogs.com/easyauthor/p/10102590.html
Copyright © 2011-2022 走看看