日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Egg.js上传图片总结

發布時間:2023/12/20 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Egg.js上传图片总结 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

使用form表單

  • 前端代碼
  • <form action="http://127.0.0.1:7001/headPicUpdate" method="post" encType="multipart/form-data"><input type="file" name="file" /><input type="submit" value="上傳" /> </form>
  • 后端代碼
  • 'use strict'; const Controller = require('egg').Controller;class userInfoUpdateController extends Controller {async headPicUpdate() { // 修改用戶頭像const path = require('path')const fs = require('fs')const { ctx } = this; let userId = this.ctx.request.body.userIdconst file = ctx.request.files[0]// 生成路徑名const toFileName = '/public/upload/' + Date.now() + file.filename;const to = path.dirname(__dirname) + toFileName;// 拷貝圖片至本地await fs.copyFileSync(file.filepath, to)// 返回前端路徑const newUrl = "http://127.0.0.1:7001" + toFileName;// 存儲到數據庫const results = await this.app.mysql.query('update user set headPicPath = ? where userId = ?', [newUrl, userId]);ctx.body = {msg: '圖片上傳成功',url: newUrl}} }module.exports = userInfoUpdateController;

    3.上傳結果

    使用axios發送請求

  • 前端代碼
  • 圖片上傳:<input id="uploadFile" type="file" name="file" />上傳按鈕:<button type="submit" onClick={upload}>Upload</button> // 上傳頭像方法const upload = () => {let file = document.querySelector('#uploadFile').files[0]let formData = new FormData()let userId = localStorage.getItem('userId')formData.append("uploadFile", file)formData.append("userId", userId)axios.post(servicePath.headPicUpdate, formData).then(function (response) {localStorage.setItem('headPicPath',response.data.url)navigate('/index/my/myDetail')console.log(response);}).catch(function (error) {console.log(error);});}
  • 后端代碼
  • 'use strict'; const Controller = require('egg').Controller;class userInfoUpdateController extends Controller {async headPicUpdate() { // 修改用戶頭像const path = require('path')const fs = require('fs')const { ctx } = this; let userId = this.ctx.request.body.userIdconst file = ctx.request.files[0]// 生成路徑名const toFileName = '/public/upload/' + Date.now() + file.filename;const to = path.dirname(__dirname) + toFileName;// 拷貝圖片至本地await fs.copyFileSync(file.filepath, to)// 返回前端路徑const newUrl = "http://127.0.0.1:7001" + toFileName;// 存儲到數據庫const results = await this.app.mysql.query('update user set headPicPath = ? where userId = ?', [newUrl, userId]);ctx.body = {msg: '圖片上傳成功',url: newUrl}} }module.exports = userInfoUpdateController;
  • 上傳結果
  • 需要注意的點

  • 使用form表單的時候,input框要添加name屬性,否則后端ctx.request.files[0]為空
  • <input type="file" name="file" />
  • 上傳multipart/form-data格式的文件,后端在config\config.default.js文件添加如下配置
  • config.multipart = {mode: 'file'};

    參考資料:

    1. egg.js文檔
    2. axios文檔

    總結

    以上是生活随笔為你收集整理的Egg.js上传图片总结的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。