目中需要上傳圖片可謂是經(jīng)常遇到的需求,本文將介紹 3 種不同的圖片上傳方式,在這總結(jié)分享一下,有什么建議或者意見(jiàn),請(qǐng)大家踴躍提出來(lái)。
沒(méi)有業(yè)務(wù)場(chǎng)景的功能都是耍流氓,那么我們先來(lái)模擬一個(gè)需要實(shí)現(xiàn)的業(yè)務(wù)場(chǎng)景。假設(shè)我們要做一個(gè)后臺(tái)系統(tǒng)添加商品的頁(yè)面,有一些商品名稱(chēng)、信息等字段,還有需要上傳商品輪播圖的需求。
我們就以Vue、Element-ui,封裝組件為例子聊聊如何實(shí)現(xiàn)這個(gè)功能。其他框架或者不用框架實(shí)現(xiàn)的思路都差不多,本文主要聊聊實(shí)現(xiàn)思路。
1.云儲(chǔ)存
常見(jiàn)的 七牛云,OSS(阿里云)等,這些云平臺(tái)提供API接口,調(diào)用相應(yīng)的接口,文件上傳后會(huì)返回圖片存儲(chǔ)在服務(wù)器上的路徑,前端獲得這個(gè)路徑保存下來(lái)提交給后端即可。此流程處理相對(duì)簡(jiǎn)單。
主要步驟
代碼范例
我們以阿里的 OSS 服務(wù)來(lái)實(shí)現(xiàn),們?cè)囍鴣?lái)封裝一個(gè)OSS的圖片上傳組件。
通過(guò)element-ui的upLoad組件的 http-request 參數(shù)來(lái)自定義我們的文件上傳,僅僅使用他組件的樣式,和其他上傳前的相關(guān)鉤子(控制圖片大小,上傳數(shù)量限制等)。
<template> <el-upload list-type="picture-card" action="''" :http-request="upload" :before-upload="beforeAvatarUpload"> <i class="el-icon-plus"></i> </el-upload> </template> <script> import {getAliOSSCreds} from '@/api/common' // 向后端獲取 OSS秘鑰信息 import {createId} from '@/utils' // 一個(gè)生產(chǎn)唯一的id的方法 import OSS from 'ali-oss' export default { name: 'imgUpload', data () { return {} }, methods: { // 圖片上傳前驗(yàn)證 beforeAvatarUpload (file) { const isLt2M = file.size / 1024 / 1024 < 2 if (!isLt2M) { this.$message.error('上傳頭像圖片大小不能超過(guò) 2MB!') } return isLt2M }, // 上傳圖片到OSS 同時(shí)派發(fā)一個(gè)事件給父組件監(jiān)聽(tīng) upload (item) { getAliOSSCreds().then(res => { // 向后臺(tái)發(fā)請(qǐng)求 拉取OSS相關(guān)配置 let creds = res.body.data let client = new OSS.Wrapper({ region: 'oss-cn-beijing', // 服務(wù)器集群地區(qū) accessKeyId: creds.accessKeyId, // OSS帳號(hào) accessKeySecret: creds.accessKeySecret, // OSS 密碼 stsToken: creds.securityToken, // 簽名token bucket: 'imgXXXX' // 阿里云上存儲(chǔ)的 Bucket }) let key = 'resource/' + localStorage.userId + '/images/' + createId() + '.jpg' // 存儲(chǔ)路徑,并且給圖片改成唯一名字 return client.put(key, item.file) // OSS上傳 }).then(res => { console.log(res.url) this.$emit('on-success', res.url) // 返回圖片的存儲(chǔ)路徑 }).catch(err => { console.log(err) }) } } } </script>
傳統(tǒng)文件服務(wù)器上傳圖片
此方法就是上傳到自己文件服務(wù)器硬盤(pán)上,或者云主機(jī)的硬盤(pán)上,都是通過(guò) formdata 的方式進(jìn)行文件上傳。具體的思路和云文件服務(wù)器差不多。
主要步驟
代碼示例
此種圖片上傳根據(jù)element-ui的upLoad組件只要傳入后端約定的相關(guān)字段即可實(shí)現(xiàn),若使用元素js也是生成formdata對(duì)象,通過(guò)Ajax去實(shí)現(xiàn)上傳也是類(lèi)似的。
這里只做一個(gè)簡(jiǎn)單的示例,具體請(qǐng)看el-upload組件相文檔就能實(shí)現(xiàn)
<template> <el-upload ref="imgUpload" :on-success="imgSuccess" :on-remove="imgRemove" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" :headers="headerMsg" :action="upLoadUrl" multiple> <el-button type="primary">上傳圖片</el-button> </el-upload> </template> <script> import {getAliOSSCreds} from '@/api/common' // 向后端獲取 OSS秘鑰信息 import {createId} from '@/utils' // 一個(gè)生產(chǎn)唯一的id的方法 import OSS from 'ali-oss' export default { name: 'imgUpload', data () { return { headerMsg:{Token:'XXXXXX'}, upLoadUrl:'xxxxxxxxxx' } }, methods: { // 上傳圖片成功 imgSuccess (res, file, fileList) { console.log(res) console.log(file) console.log(fileList) // 這里可以獲得上傳成功的相關(guān)信息 } } } </script>
圖片轉(zhuǎn) base64 后上傳
有時(shí)候做一些私活項(xiàng)目,或者一些小圖片上傳可能會(huì)采取前端轉(zhuǎn)base64后成為字符串上傳。當(dāng)我們有這一個(gè)需求,有一個(gè)商品輪播圖多張,轉(zhuǎn)base64編碼后去掉data:image/jpeg;base64,將字符串以逗號(hào)的形勢(shì)拼接,傳給后端。我們?nèi)绾蝸?lái)實(shí)現(xiàn)呢。
1.本地文件如何轉(zhuǎn)成 base64
我們通過(guò)H5新特性 readAsDataURL 可以將文件轉(zhuǎn)base64格式,輪播圖有多張,可以在點(diǎn)擊后立馬轉(zhuǎn)base64也可,我是在提交整個(gè)表單錢(qián)一次進(jìn)行轉(zhuǎn)碼加工。
具體步驟
在這里要注意一下,因?yàn)?readAsDataURL 操作是異步的,我們?nèi)绾螌⒋嬖跀?shù)組中的若干的 file對(duì)象,進(jìn)行編碼,并且按照上傳的順序,把編碼后端圖片base64字符串儲(chǔ)存在一個(gè)新數(shù)組內(nèi)呢,首先想到的是promise的鏈?zhǔn)秸{(diào)用,可是不能并發(fā)進(jìn)行轉(zhuǎn)碼,有點(diǎn)浪費(fèi)時(shí)間。我們可以通過(guò)循環(huán) async 函數(shù)進(jìn)行并發(fā),并且排列順序。請(qǐng)看 methods 的 submitData 方法
utils.js
export function uploadImgToBase64 (file) { return new Promise((resolve, reject) => { const reader = new FileReader() reader.readAsDataURL(file) reader.onload = function () { // 圖片轉(zhuǎn)base64完成后返回reader對(duì)象 resolve(reader) } reader.onerror = reject }) }
添加商品頁(yè)面 部分代碼
<template> <div> <el-upload ref="imgBroadcastUpload" :auto-upload="false" multiple :file-list="diaLogForm.imgBroadcastList" list-type="picture-card" :on-change="imgBroadcastChange" :on-remove="imgBroadcastRemove" accept="image/jpg,image/png,image/jpeg" action=""> <i class="el-icon-plus"></i> <div slot="tip" class="el-upload__tip">只能上傳jpg/png文件,且不超過(guò)2M</div> </el-upload> <el-button>submitData</el-button> </div> </template> <script> import { uploadImgToBase64 } from '@/utils' // 導(dǎo)入本地圖片轉(zhuǎn)base64的方法 export default { name: 'imgUpload', data () { return { diaLogForm: { goodsName:'', // 商品名稱(chēng)字段 imgBroadcastList:[], // 儲(chǔ)存選中的圖片列表 imgsStr:'' // 后端需要的多張圖base64字符串 , 分割 } } }, methods: { // 圖片選擇后 保存在 diaLogForm.imgBroadcastList 對(duì)象中 imgBroadcastChange (file, fileList) { const isLt2M = file.size / 1024 / 1024 < 2 // 上傳頭像圖片大小不能超過(guò) 2MB if (!isLt2M) { this.diaLogForm.imgBroadcastList = fileList.filter(v => v.uid !== file.uid) this.$message.error('圖片選擇失敗,每張圖片大小不能超過(guò) 2MB,請(qǐng)重新選擇!') } else { this.diaLogForm.imgBroadcastList.push(file) } }, // 有圖片移除后 觸發(fā) imgBroadcastRemove (file, fileList) { this.diaLogForm.imgBroadcastList = fileList }, // 提交彈窗數(shù)據(jù) async submitDialogData () { const imgBroadcastListBase64 = [] console.log('圖片轉(zhuǎn)base64開(kāi)始...') // 并發(fā) 轉(zhuǎn)碼輪播圖片list => base64 const filePromises = this.diaLogForm.imgBroadcastList.map(async file => { const response = await uploadImgToBase64(file.raw) return response.result.replace(/.*;base64,/, '') // 去掉data:image/jpeg;base64, }) // 按次序輸出 base64圖片 for (const textPromise of filePromises) { imgBroadcastListBase64.push(await textPromise) } console.log('圖片轉(zhuǎn)base64結(jié)束..., ', imgBroadcastListBase64) this.diaLogForm.imgsStr = imgBroadcastListBase64.join() console.log(this.diaLogForm) const res = await addCommodity(this.diaLogForm) // 發(fā)請(qǐng)求提交表單 if (res.status) { this.$message.success('添加商品成功') // 一般提交成功后后端會(huì)處理,在需要展示商品地方會(huì)返回一個(gè)圖片路徑 } }, } } </script>
這樣本地圖片上傳的時(shí)候轉(zhuǎn)base64上傳就完成了。可是輪播圖有可以進(jìn)行編輯,我們?cè)撊绾翁幚砟兀恳话銇?lái)說(shuō)商品增加頁(yè)面和修改頁(yè)面可以公用一個(gè)組件,那么我們繼續(xù)在這個(gè)頁(yè)面上修改。
編輯時(shí)我們首先會(huì)拉取商品原有數(shù)據(jù),進(jìn)行展示,在進(jìn)行修改,這時(shí)候服務(wù)器返回的圖片是一個(gè)路徑 http://xxx.xxx.xxx/abc.jpg 這樣,當(dāng)我們新增一張圖片的還是和上面的方法一樣轉(zhuǎn)碼即可。可是后端說(shuō),沒(méi)有修改的圖片也要賺base64轉(zhuǎn)過(guò)來(lái),好吧那就做把。這是一個(gè)在線(xiàn)鏈接 圖片,不是本地圖片,怎么做呢?
2. 在線(xiàn)圖片轉(zhuǎn)base64
具體步驟
utils.js 文件添加在線(xiàn)圖片轉(zhuǎn)base64的方法,利用canvas
編輯商品,先拉取原來(lái)的商品信息展示到頁(yè)面
提交表單之前,區(qū)分在線(xiàn)圖片還是本地圖片進(jìn)行轉(zhuǎn)碼
utils.js
export function uploadImgToBase64 (file) { return new Promise((resolve, reject) => { function getBase64Image (img) { const canvas = document.createElement('canvas') canvas.width = img.width canvas.height = img.height const ctx = canvas.getContext('2d') ctx.drawImage(img, 0, 0, canvas.width, canvas.height) var dataURL = canvas.toDataURL() return dataURL } const image = new Image() image.crossOrigin = '*' // 允許跨域圖片 image.src = img + '?v=' + Math.random() // 清除圖片緩存 console.log(img) image.onload = function () { resolve(getBase64Image(image)) } image.onerror = reject }) }
添加商品頁(yè)面 部分代碼
<template> <div> <el-upload ref="imgBroadcastUpload" :auto-upload="false" multiple :file-list="diaLogForm.imgBroadcastList" list-type="picture-card" :on-change="imgBroadcastChange" :on-remove="imgBroadcastRemove" accept="image/jpg,image/png,image/jpeg" action=""> <i class="el-icon-plus"></i> <div slot="tip" class="el-upload__tip">只能上傳jpg/png文件,且不超過(guò)2M</div> </el-upload> <el-button>submitData</el-button> </div> </template> <script> import { uploadImgToBase64, URLImgToBase64 } from '@/utils' export default { name: 'imgUpload', data () { return { diaLogForm: { goodsName:'', // 商品名稱(chēng)字段 imgBroadcastList:[], // 儲(chǔ)存選中的圖片列表 imgsStr:'' // 后端需要的多張圖base64字符串 , 分割 } } }, created(){ this.getGoodsData() }, methods: { // 圖片選擇后 保存在 diaLogForm.imgBroadcastList 對(duì)象中 imgBroadcastChange (file, fileList) { const isLt2M = file.size / 1024 / 1024 < 2 // 上傳頭像圖片大小不能超過(guò) 2MB if (!isLt2M) { this.diaLogForm.imgBroadcastList = fileList.filter(v => v.uid !== file.uid) this.$message.error('圖片選擇失敗,每張圖片大小不能超過(guò) 2MB,請(qǐng)重新選擇!') } else { this.diaLogForm.imgBroadcastList.push(file) } }, // 有圖片移除后 觸發(fā) imgBroadcastRemove (file, fileList) { this.diaLogForm.imgBroadcastList = fileList }, // 獲取商品原有信息 getGoodsData () { getCommodityById({ cid: this.diaLogForm.id }).then(res => { if (res.status) { Object.assign(this.diaLogForm, res.data) // 把 '1.jpg,2.jpg,3.jpg' 轉(zhuǎn)成[{url:'http://xxx.xxx.xx/j.jpg',...}] 這種格式在upload組件內(nèi)展示。 imgBroadcastList 展示原有的圖片 this.diaLogForm.imgBroadcastList = this.diaLogForm.imgsStr.split(',').map(v => ({ url: this.BASE_URL + '/' + v })) } }).catch(err => { console.log(err.data) }) }, // 提交彈窗數(shù)據(jù) async submitDialogData () { const imgBroadcastListBase64 = [] console.log('圖片轉(zhuǎn)base64開(kāi)始...') this.dialogFormLoading = true // 并發(fā) 轉(zhuǎn)碼輪播圖片list => base64 const filePromises = this.diaLogForm.imgBroadcastList.map(async file => { if (file.raw) { // 如果是本地文件 const response = await uploadImgToBase64(file.raw) return response.result.replace(/.*;base64,/, '') } else { // 如果是在線(xiàn)文件 const response = await URLImgToBase64(file.url) return response.replace(/.*;base64,/, '') } }) // 按次序輸出 base64圖片 for (const textPromise of filePromises) { imgBroadcastListBase64.push(await textPromise) } console.log('圖片轉(zhuǎn)base64結(jié)束...') this.diaLogForm.imgs = imgBroadcastListBase64.join() console.log(this.diaLogForm) if (!this.isEdit) { // 新增編輯 公用一個(gè)組件。區(qū)分接口調(diào)用 const res = await addCommodity(this.diaLogForm) // 提交表單 if (res.status) { this.$message.success('添加成功') } } else { const res = await modifyCommodity(this.diaLogForm) // 提交表單 if (res.status) { this.$router.push('/goods/goods-list') this.$message.success('編輯成功') } } } } } </script>
結(jié)語(yǔ)
至此常用的三種圖片上傳方式就介紹完了,轉(zhuǎn)base64方式一般在小型項(xiàng)目中使用,大文件上傳還是傳統(tǒng)的 formdata或者 云服務(wù),更合適。但是 通過(guò)轉(zhuǎn)base64方式也使得,在前端進(jìn)行圖片編輯成為了可能,不需要上傳到服務(wù)器就能預(yù)覽。主要收獲還是對(duì)于異步操作的處理。
以下是總結(jié)出來(lái)最全前端框架視頻,包含: javascript/vue/react/angualrde/express/koa/webpack 等學(xué)習(xí)資料。
.需求
最近我們公司在做一個(gè)官網(wǎng)涉及到圖片視頻上傳的問(wèn)題,時(shí)間比較緊急(實(shí)際后端想偷懶),就讓我直傳視頻到阿里云的oss上。我一聽(tīng),也是一臉懵,人在家中坐,鍋從天上來(lái)。話(huà)不多說(shuō),我直沖度娘,網(wǎng)上的案例真的是非常的多,眼花繚亂,我也試了幾個(gè)發(fā)現(xiàn)都是有問(wèn)題的,又聯(lián)系不到博主,最終我還是放棄了,干脆自己搞一個(gè)吧,經(jīng)過(guò)三天三夜的奮戰(zhàn)(其實(shí)是一晚上)!所以分享出來(lái)給各位小伙伴們,希望早日脫坑!
先上效果圖
2.阿里oss的安裝
npm install ali-oss --save
3.封裝oss通用上傳js工具類(lèi)
"use strict";
import { dateFormat } from './utils.js'
var OSS = require("ali-oss");
let url='';
export default {
/**
* 創(chuàng)建隨機(jī)字符串
* @param num
* @returns {string}
*/
randomString(num) {
const chars = [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z"
];
let res = "";
for (let i = 0; i < num; i++) {
var id = Math.ceil(Math.random() * 35);
res += chars[id];
}
return res;
},
/**
* 創(chuàng)建oss客戶(hù)端對(duì)象
* @returns {*}
*/
createOssClient() {
return new Promise((resolve, reject) => {
const client = new OSS({
region: "XXXXX", // 請(qǐng)?jiān)O(shè)置成你的
accessKeyId: "XXXXX", // 請(qǐng)?jiān)O(shè)置成你的
accessKeySecret: "XXXXX", // 請(qǐng)?jiān)O(shè)置成你的
bucket: "XXXXX", // 請(qǐng)?jiān)O(shè)置成你的
secure: true // 上傳鏈接返回支持https
});
resolve(client);
});
},
/**
* 文件上傳
* @param option 參考csdn: https://blog.csdn.net/qq_27626333/article/details/81463139
*/
ossUploadFile(option) {
const file = option.file;
const self = this;
// var url = '';
return new Promise((resolve, reject) => {
const date = dateFormat(new Date(), "yyyyMMdd"); // 當(dāng)前時(shí)間
const dateTime = dateFormat(new Date(), "yyyyMMddhhmmss"); // 當(dāng)前時(shí)間
const randomStr = self.randomString(4); // 4位隨機(jī)字符串
const extensionName = file.name.substr(file.name.indexOf(".")); // 文件擴(kuò)展名
const fileName =
"video/" + date + "/" + dateTime + "_" + randomStr + extensionName; // 文件名字(相對(duì)于根目錄的路徑 + 文件名)
// 執(zhí)行上傳
self.createOssClient().then(client => {
// 異步上傳,返回?cái)?shù)據(jù)
resolve({
fileName: file.name,
fileUrl: fileName
});
// 上傳處理
// 分片上傳文件
client
.multipartUpload(fileName, file, {
progress: function(p) {
const e = {};
e.percent = Math.floor(p * 100);
// console.log('Progress: ' + p)
option.onProgress(e);
}
})
.then(
val => {
window.url = val
console.info('woc',url);
if (val.res.statusCode === 200) {
option.onSuccess(val);
return val;
} else {
option.onError("上傳失敗");
}
},
err => {
option.onError("上傳失敗");
reject(err);
}
);
});
});
}
};
4.在src下的util文件創(chuàng)建utils.js工具類(lèi)
/**
* 時(shí)間日期格式化
* @param format
* @returns {*}
*/
export const dateFormat = function(dateObj, format) {
const date = {
"M+": dateObj.getMonth() + 1,
"d+": dateObj.getDate(),
"h+": dateObj.getHours(),
"m+": dateObj.getMinutes(),
"s+": dateObj.getSeconds(),
"q+": Math.floor((dateObj.getMonth() + 3) / 3),
"S+": dateObj.getMilliseconds()
};
if (/(y+)/i.test(format)) {
format = format.replace(
RegExp.$1,
(dateObj.getFullYear() + "").substr(4 - RegExp.$1.length)
);
}
for (const k in date) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(
RegExp.$1,
RegExp.$1.length === 1
? date[k]
: ("00" + date[k]).substr(("" + date[k]).length)
);
}
}
return format;
};
5.vue頁(yè)面中的使用
<template>
<div>
<el-form :model="form" label-width="80px" size="small">
<el-form-item label="上傳視頻">
<el-upload class="upload-demo" action=""
:http-request="fnUploadRequest"
:show-file-list="true"
:limit=1
:on-exceed="beyondFile"
:on-success="handleVideoSuccess"
:before-upload="beforeUploadVideo">
<div tabindex="0" class="el-upload-video">
<i class="el-upload-video-i el-icon-plus avatar-uploader-icon"></i>
</div>
<div class="el-upload__tip" slot="tip">上傳視頻文件,且不超過(guò)500mb</div>
</el-upload>
<el-input type="textarea" rows="5" v-model="urls"></el-input>
</el-form-item>
</el-form>
</div>
</template>
6.js中的代碼
<script>
import oss from '../../util/oss.js'
export default {
data: function() {
return {
form: {
status: true
},
url:[],
urls:''
}
},
methods: {
/**
* @description [fnUploadRequest 覆蓋默認(rèn)的上傳行為,實(shí)現(xiàn)自定義上傳]
* @param {object} option [上傳選項(xiàng)]
* @return {null} [沒(méi)有返回]
*/
async fnUploadRequest(option) {
oss.ossUploadFile(option);
},
// 視頻上傳
beforeUploadVideo(file) {
// todo
},
// 視頻上傳成功后
handleVideoSuccess(response, file, fileList) {
console.log('url',window.url);
console.log('url',window.url.res.requestUrls);
this.url = window.url.res.requestUrls;
console.log('3322',this.url.length)
for(var i = 0;i<this.url.length;i++){
console.log('href',this.url[i])
this.urls = this.url[i].split('?')[0]
console.log('jjjj',this.url)
}
// todo
},
// 視頻添加多個(gè)視頻文件事件
beyondFile(files, fileList) {
},
}
}
</script>
7.css代碼
<style lang="less" scoped>
.el-upload-video {
width: 100px;
height: 100px;
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.el-upload-video-i{
font-size: 36px;
padding-top: 25px;
color: #8c939d;
width: 50px;
height: 50px;
line-height: 50px;
text-align: center;
}
</style>
8.總結(jié)
我在這里講一下需要注意的幾點(diǎn):
1.這個(gè)我沒(méi)有貼出阿里云的一些配置,自己可以問(wèn)問(wèn)度娘,網(wǎng)上有很多資料,注意跨域的配置就行。
2.這樣做的優(yōu)點(diǎn)就是不用和后端交互,圖片直傳到你阿里云的oss然后返回鏈接,不需要后端的傳值,省去了很多和后端人員聯(lián)調(diào)的時(shí)間,大大提高了開(kāi)發(fā)的效率。
代碼我已經(jīng)都貼出來(lái)了,樣式的話(huà)可以自己改,這個(gè)是可以根據(jù)自己的需求來(lái)更改的,如果還有什么問(wèn)題的話(huà),歡迎留言評(píng)論!
圖片來(lái)源于網(wǎng)絡(luò)
是一個(gè)包含了函數(shù)計(jì)算每種 Runtime 結(jié)合 HTTP Trigger 實(shí)現(xiàn)文件上傳和文件下載的示例集。每個(gè)示例包括:
我們知道不同語(yǔ)言在處理 HTTP 協(xié)議上傳下載時(shí)都有很多中方法和社區(qū)庫(kù),特別是結(jié)合函數(shù)計(jì)算的場(chǎng)景,開(kāi)發(fā)人員往往需要耗費(fèi)不少精力去學(xué)習(xí)和嘗試。本示例集編撰的目的就是節(jié)省開(kāi)發(fā)者甄別的精力和時(shí)間,為每種語(yǔ)言提供一種有效且符合社區(qū)最佳實(shí)踐的方法,可以拿來(lái)即用。
當(dāng)前已支持的 Runtime 包括:
計(jì)劃支持的 Runtime 包括:
不打算支持的 Runtime 包括:
由于函數(shù)計(jì)算對(duì)于 HTTP 的 Request 和 Response 的 Body 大小限制均為 6M,所以該示例集只適用于借助函數(shù)計(jì)算上傳和下載文件小于 6M 的場(chǎng)景。對(duì)于大于 6M 的情況,可以考慮如下方法:
在開(kāi)始之前請(qǐng)確保開(kāi)發(fā)環(huán)境已經(jīng)安裝了如下工具:
克隆代碼:
git clone https://github.com/vangie/fc-file-transfer
本地啟動(dòng)函數(shù):
$ make start
...
HttpTrigger httpTrigger of file-transfer/nodejs was registered
url: http://localhost:8000/2016-08-15/proxy/file-transfer/nodejs
methods: [ 'GET', 'POST' ]
authType: ANONYMOUS
HttpTrigger httpTrigger of file-transfer/python was registered
url: http://localhost:8000/2016-08-15/proxy/file-transfer/python
methods: [ 'GET', 'POST' ]
authType: ANONYMOUS
HttpTrigger httpTrigger of file-transfer/java was registered
url: http://localhost:8000/2016-08-15/proxy/file-transfer/java
methods: [ 'GET', 'POST' ]
authType: ANONYMOUS
HttpTrigger httpTrigger of file-transfer/php was registered
url: http://localhost:8000/2016-08-15/proxy/file-transfer/php
methods: [ 'GET', 'POST' ]
authType: ANONYMOUS
function compute app listening on port 8000!
make start 命令會(huì)調(diào)用 Makefile 文件中的指令,通過(guò) fun local 在本地的 8000 端口開(kāi)放 HTTP 服務(wù),控制臺(tái)會(huì)打印出每個(gè) HTTP Trigger 的 URL 、支持的 HTTP 方法,以及認(rèn)證方式。
上面四個(gè) URL 地址隨便選一個(gè)在瀏覽器中打開(kāi)示例頁(yè)面。
所有示例都實(shí)現(xiàn)了下述四個(gè) HTTP 接口:
此外為了能正確的計(jì)算相對(duì)路徑,在訪問(wèn)根路徑時(shí)如果不是以/結(jié)尾,都會(huì)觸發(fā)一個(gè) 301 跳轉(zhuǎn),在 URL 末尾加上一個(gè)/。
查看更多:https://yq.aliyun.com/articles/743642?utm_content=g_1000103098
上云就看云棲號(hào):更多云資訊,上云案例,最佳實(shí)踐,產(chǎn)品入門(mén),訪問(wèn):https://yqh.aliyun.com/
*請(qǐng)認(rèn)真填寫(xiě)需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。