HTML5+AJAX+WEBAPI 文件上传

总体的思路是把文件转换成base64字符串传递给后台,然后再把base64字符串转换成二进制,转成文件。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>�򵥵�html5 File���� for pic2base64</title>
    <script src="Scripts/jquery-1.8.2.js"></script>
    <style>
    </style>
    <script>
        window.onload = function () {
            var input = document.getElementById("demo_input");
            var result = document.getElementById("result");
            var img_area = document.getElementById("img_area");
            if (typeof (FileReader) === 'undefined') {
                result.innerHTML = "��Ǹ������������֧�� FileReader����ʹ���ִ������������";
                input.setAttribute('disabled', 'disabled');
            } else {
                input.addEventListener('change', readFile, false);
            }
        }
        function readFile() {
            var file = this.files[0];
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function (e) {
                result.value = this.result;
            
                $.ajax({             
                    type: "POST",
                    url: "神秘的URL/api/TabCompany/POSTUploadCompanyWeChatImg",
                    data: { "base64": result.value, "type": ".jpg" },//所有上传文件统一为此对象。result.value 不再截取。type 为文件类型,带.
                    success: function (data) {         
                        alert("6666666");
                        alert(data);                
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(XMLHttpRequest.status);
                        alert(XMLHttpRequest.readyState);
                        alert(textStatus);
                    }
                });
              
            }
        }
    </script>
</head>
<body>
    <input type="file" value="sdgsdg" id="demo_input" />
    <textarea id="result" rows=30 cols=300></textarea>
    <p id="img_area"></p>
</body>
</html>

后端代码如下

   public string POSTUploadCompanyWeChatImg([FromBody]file base64)
        {
            quence = new ConsenQuance();
            try
            {
                string type = base64.type;
                string base64str = base64.base64.Split(',')[1];
                byte[] data = Convert.FromBase64String(base64str);
                string savePath = "/FileCompanyWeCha/"; //虚拟路径,项目中的虚拟路径。一般我们条用这个方法,肯定要把生成的word文档保存在项目的一个文件夹下,以备后续使用
                string path = ResumePath;//System.Web.HttpContext.Current.Server.MapPath(savePath); //把相应的虚拟路径转换成物理路径
                if (!System.IO.Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                savePath += Guid.NewGuid().ToString() + type;
                string filePath = ResumePath + savePath;// System.Web.HttpContext.Current.Server.MapPath(savePath);
                FileStream fs;
                if (System.IO.File.Exists(filePath))
                {
                    fs = new FileStream(filePath, FileMode.Truncate);
                }
                else
                {
                    fs = new FileStream(filePath, FileMode.CreateNew);
                }
                BinaryWriter br = new BinaryWriter(fs);
                br.Write(data, 0, data.Length);
                br.Close();
                fs.Close();

                if (System.IO.File.Exists(filePath))
                {
                    quence.Result = true;
                    quence.ReturnStr = savePath;
                }
                else
                {
                    quence.Result = false;
                    quence.ErrMsg = "服务器创建文档失败";
                }
            }
            catch (Exception ex)
            {
                quence.Result = false;
                quence.ErrMsg = ex.Message;
            }
            return JsonHelp.JsonSerializer<ConsenQuance>(quence);
        }
 
参数实体类
  public   class file
    {
        public string base64 { get; set; }
        public string type { get; set; }
    }

 

用这个代码。并不存在跨域问题。

AJAX解决跨域问题是很郁闷的事情。

另外值得一提的是。WEBAPI的POST请求和WEBSERVICE的是不同的。

posted @ 2016-05-31 23:02  code_dream  阅读(5707)  评论(0编辑  收藏  举报