node上傳圖片到Java
阿新 • • 發佈:2019-02-02
npm install --save form-data
npm install --save axios
var fs = require('fs');
var axios = require('axios');
let data = fs.createReadStream(__dirname + '/../public/wx/coupon.png')
let form = new FormData()
form.append('type','image')
form.append('media',data,'test.jpg')
let getHeaders = (form=>{
return new Promise((resolve,reject)=>{
form.getLength((err,length)=>{
if(err) reject(err)
let headers = Object.assign({'Content-Length':length},form.getHeaders())
resolve(headers)
})
})
})
getHeaders(form).then(headers=>{
return axios.post(url,form,{headers:headers})
}) .then((response)=>{
console.log('圖片上傳成功-永久', response.data)
}).catch(e=>{console.log('上傳圖片出錯-永久', e)})