当前位置: 首页 > 后端技术 > Node.js

优派云Node.js实现文件上传删除

时间:2023-04-03 16:42:29 Node.js

Node.js服务器使用Node.js+Express.js实现服务器constexpress=require("express");constapp=express();constaxios=require('axios');app.set('port',process.env.PORT||8082);//静态资源目录,这里放在根目录下,生产环境不允许这样app.use(express.static(__dirname));//启动一个serverwith端口8082app.listen(app.get('port'),()=>{console.log("http://localhost:"+app.get('port'));});PrepareBase64,HMAC-SHA1,MD5实现签名认证细节见:http://docs.upyun.com/api/aut...constcrypto=require("crypto");//MD5functionMD5(value){returncrypto.createHash("md5").update(value).digest("hex");}//Base64functionbase64(value){returnBuffer.from(value).toString("base64");}//hmacsha1functionhmacsha1(secret,value){returncrypto.createHmac('sha1',secret).update(value,'utf-8').digest().toString('base64');}上传、删除接口constdate=newDate().toGMTString();const桶名="";//空间名称constkey="";//运算符constsecret="";//密码constupyunUrl='http://v0.api.upyun.com/'//上传应用。得到(“/API/吨oken/upload",(req,res)=>{letfileName=(Math.random()*100000000)>>>0;letexpiration=((Date.now()/1000)>>>0)+30*60;//请求过期时间,UNIXUTC时间戳,单位秒,建议设置为30分钟http://docs.upyun.com/api/form_api/letmethod="POST";letpolicy=base64(JSON.stringify({bucket:bucketname,//"save-key":"/"+fileName+"{.suffix}","save-key":"/{filename}{.suffix}",expiration:expiration}));letauthorization="UPYUN"+key+":"+hmacsha1(MD5(secret),method+"&/"+bucketname+"&"+policy);res.json({msg:"OK",code:200,data:{authorization:authorization,policy:policy}});});//Deleteapp.get('/api/token/del',(req,res)=>{letitem=req.query.item;letmethod="DELETE"letauthorization="UPYUN"+key+":"+hmacsha1(MD5(secret),method+'&/'+bucketname+item+'&'+date);axios({url:upyunUrl+bucketname+item,method:'DELETE',headers:{'Authorization':authorization,'Date':date}}).then(response=>{res.json({msg:"OK",代码:200,data:{}});}).catch(err=>{console.log('err',err)})})跨域接口调用constcors=require('cors');//CORS@seehttps://github.com/expressjs/corsapp.use(cors());前端前端使用Vue.js实现引入Bootstrap.cssUPYun上传&删除上传

    {{item}}删除
引入Vue.js、Axiosscriptsrc="https://unpkg.com/axios/dist/axios.min.js">JSconstupUrl='http://v0.api.upyun.com/'//+空间名,如:http://v0.api.upyun.com/yun-tempconstbaseApi='http://localhost:8082/api/'letuploadInput;letapp=newVue({el:'#app',data:{files:[]},methods:{onChange:function(){getToken(token=>{letformData=newFormData();formData.append("file",uploadInput.files[0])formData.append('policy',token.policy)formData.append("authorization",token.authorization)axios({方法:'POST',url:upUrl,数据:formData}).then(res=>{res=res||{}if(res.status!==200){console.log('error')return}letdata=res.data||{}this.files.push(data.url)alert('Success')}).catch(err=>{console.log(err);});});},onDel:function(item,index){this.files.splice(index,1)axios.request({url:baseApi+'token/del',method:'GET',params:{item:encodeURI(item)}}).then(res=>{alert('Deleted.')}).catch(err=>{console.log(err)})}},mounted(){uploadInput=$('file')}})//DOM获取元素函数$(el){returndocument.getElementById(el)}//获取token函数getToken(fn){lettoken=window.localStorage.getItem('token');令牌=JSON.parse(令牌)||{};让nowTime=Date.now();if(nowTime{letdata=res.data||{}data=data.data||{}constauthorization=data.authorizationconstpolicy=data.policyconstexpired=((Date.now()/1000)>>>0)+30*60;token={授权,策略,过期}fn(token)window.localStorage.setItem('token',JSON.stringify(token))});}项目源码https://github.com/givebest/UPyun-upload-delete-node.js转载请注明出处:https://blog.givebest。cn/other/2018/10/27/upyun-upload-delete-node.js.html