Hightlight.js-9.15.6

顯示具有 web 標籤的文章。 顯示所有文章
顯示具有 web 標籤的文章。 顯示所有文章

2019年3月23日 星期六

[Web] 利用FileSaver.js使瀏覽器彈出存檔視窗儲存前端資料

在撰寫前端程式(ex:Single Pag Application)時,有時需要使用者儲存使用者端產生的資料,這時候可以使用FileSaver.js,任何轉換成Web API中的Blob物件的資料都能夠使用FileSaver.js存檔,因此在使用FileSaver.js之前至少要了解什麼是Blob物件、以及Blob建構式。



Blob物件

在MDN上關於Blob(Binary Large Object)的描述是"類檔案的不可變原始資料物件"(a file-like object of immutable, raw data),而File介面就是繼承Blob,並增強瀏覽器使用者系統上檔案的操作功能,要實現儲存前端資料這個功能可以先了解Blob建構式。...但值得謹記在心的是目前為止Android上主流瀏覽器對Blob的支援不明朗


Blob建構式

// Blob物件建構式語法:
let Blob = new Blob(array [, options]);

array是建構式必要的參數,是ArrayBuffer、ArrayBufferView、Blob、DOMString組成的Array物件或多種型別混合的陣列。

options作為一個物件傳入建構式,可以有兩種key:type跟endings:

type是對Blob型別描述(例如:text/csv、image/jpeg...),沒有預設值(type: ""),選項可以參考MDN上的MIME type

endings則可以指定對行尾\n的處理方式預設選項是"transparent"會保留\n為換行符號,如果指定為"native"就會將\n轉換為各OS定義的換行符號。

延伸學習

Blob Properties、Blob Methods、File API



FileSaver.js範例:

這裡的範例都是參考官方網站上改成cdn引入的,而測試的時候儲存遠端URL資源似乎無法使用?另外官網也提供用Web API 的 File產生Blob物件再套入saveAs(),這部分可以自行延伸。

儲存文字

<script src="https://fastcdn.org/FileSaver.js/1.1.20151003/FileSaver.min.js"></script>
<script>
  let blob = new Blob(["Hello, FileSaver.js!"], {type: "text/plain;charset=utf-8"});
  saveAs(blob, "hello.txt");
</script>

儲存convas

原理是Canvas元素用HTMLCanvasElement.toBlob()轉換成Blob,再存檔。
<script src="https://fastcdn.org/FileSaver.js/1.1.20151003/FileSaver.min.js"></script>
<script>
  let canvas = document.getElementById("canvasId");
  canvas.toBlob(blob =>
    saveAs(blob, "pretty image.png");
  );
</script>

2018年12月18日 星期二

[Web] 以iris建立允許CORS請求的JSON API server

先決基礎知識

Golang, JavaScript, ES6

學習目標

網路知識:到MDN了解什麼是跨來源資源共用 Cross-Origin Resource Sharing (CORS)。
JSON server: 將iris Application掛載可自動發送CORS標頭的cors中間件 (GithubGoDoc說明文件官方範例程式)
Web Client:參考MDN的Fetch API使用方法,用JavaScript從遠端取得資料。

程式碼

JSON server:
package main

import (
  "github.com/iris-contrib/middleware/cors"
  "github.com/kataras/iris"
)

type tmp struct {
  ValBool    bool   `json:"valBool"`
  ValString  string `json:"valString"`
}

func main() {

  // 建立一個允許cors的context.Handler
  crs := cors.AllowAll()

  // 建立iris Application,並且掛載crs作為middleware
  app := iris.New()
  app.Use(crs)
  app.AllowMethods(iris.MethodOptions)

  app.Post("/api", func(ctx iris.Context) {
    j := tmp{
      ValBool:     true,
      ValString:   "abc",
    }
    ctx.JSON(j)
  })
  app.Run(iris.Addr(":38080"), iris.WithCharset("UTF-8"))
}

Web client (按F12在Chrome的console中查看結果):
<script type= application/javascript>
 var url = "http://localhost:38080/api";
   fetch(url, {
    method: 'POST',
    body: JSON.stringify({}),
    credentials: 'include',
    mode: 'cors',
    headers: {
      'Content-Type': 'application/json',
    },
  })
    .then(res=>res.json())
    .catch(error => console.error('Error:', error))
    .then((res)=>console.log(res))
</script>