HTML5+AJAX+WEBAPI 文件上傳

整體的思路是把文件轉換成base64字符串傳遞給後臺,而後再把base64字符串轉換成二進制,轉成文件。html

<!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>

後端代碼以下html5

   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; }
    }

 

用這個代碼。並不存在跨域問題。jquery

AJAX解決跨域問題是很鬱悶的事情。ajax

另外值得一提的是。WEBAPI的POST請求和WEBSERVICE的是不一樣的。後端

相關文章
相關標籤/搜索