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

錯(cuò)誤提示
將本地的 http 請(qǐng)求變成 https 請(qǐng)求,搞這個(gè)還是有些費(fèi)時(shí)間的,我嘗試了nginx做代理,但是奈何不懂用法的含義,不知道為什么沒有效果,還是要好好研究一下 nginx 使用方法。
然后我就換了另外一種方法,也是比較簡(jiǎn)單的。參考原文 Calling HTTPS URLs from http://localhost
在 ~ .zshrc (如果你用的是oh my zsh) 中加入下面這一行配置,然后 source .zshrc使配置生效。然后在命令行輸入chrome 自動(dòng)打開一個(gè)頁(yè)面,然后就可以發(fā)送請(qǐng)求了。
alias chrome=”/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --disable-web-security --user-data-dir=~/.chrome-disable-web-security”
調(diào)用api
項(xiàng)目是基于 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
關(guān)鍵在于,請(qǐng)求圖片時(shí),設(shè)置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 });
});
}