項目需求
需要在input標簽上傳圖片文件時刨仑,能夠先經過壓縮,然后在上傳到遠程服務器苫耸,以減少服務器內存的占用。經過調研儡陨,發(fā)現(xiàn) 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 });
});
}