項目需求
需要在input標簽上傳圖片文件時,能夠先經過壓縮,然后在上傳到遠程服務器,以減少服務器內存的占用。經過調研,發(fā)現 tinify 在眾多圖片壓縮中,效果比較好。
使用方法
申請ApiKey
通過郵箱申請賬號,獲取 ApiKey
設置本地開發(fā)環(huán)境
tinify 開發(fā)文檔中有說明,所有的請求都要通過 HTTPS 連接進行。那么問題來了,本地開發(fā)環(huán)境是localhost 或者 127.0.0.1啊,是 HTTP連接,怎么辦呢?
直接上,強行請求的結果是 404

錯誤提示
將本地的 http 請求變成 https 請求,搞這個還是有些費時間的,我嘗試了nginx做代理,但是奈何不懂用法的含義,不知道為什么沒有效果,還是要好好研究一下 nginx 使用方法。
然后我就換了另外一種方法,也是比較簡單的。參考原文 Calling HTTPS URLs from http://localhost
在 ~ .zshrc (如果你用的是oh my zsh) 中加入下面這一行配置,然后 source .zshrc使配置生效。然后在命令行輸入chrome 自動打開一個頁面,然后就可以發(fā)送請求了。
alias chrome=”/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --disable-web-security --user-data-dir=~/.chrome-disable-web-security”
調用api
項目是基于 angular 的,url 是壓縮后圖片的連接,type 是壓縮后圖片的類型
compress(file: File | Blob, apiKey: string): Observable<{url: string, type: string}> {
const headers = new Headers();
const key = btoa(`api:${apiKey}`);
headers.append('Authorization', `Basic ${key}`);
return this.http.post('https://api.tinify.com/shrink', file, { headers }).map(resp => {
const data = resp.json();
return {
url: data.output.url,
type: data.output.type
};
});
}
從圖片連接獲取到 File
關鍵在于,請求圖片時,設置responseType 為 ArrayBuffer類型
getCompressImage(url: string, type: string, apiKey: string): Observable<File> {
const headers = new Headers();
const key = btoa(`api:${apiKey}`);
headers.append('Authorization', `Basic ${key}`);
return this.http.get(url, { headers: headers, responseType: ResponseContentType.ArrayBuffer }).map(resp => {
return new File([resp.arrayBuffer()], 'result.png', { type: type });
});
}