簡體   English   中英

我正在嘗試使用 React js 將圖像上傳到 nodejs api,我需要幫助如何上傳

[英]I am trying to upload image to the nodejs api using React js and i need help how to upload

創建異步重擊: 在此處輸入圖像描述 這是我的節點 js api 路由router.post('/', upload.single('image'), protect, setAd)

這是我的反應 js 代碼export const sellBike = (bikeData) => API.post("/", bikeData);

我的反應 js api const API = axios.create({baseURL:"http://localhost:8000"});

通常為了在 nodejs 上上傳照片,他們使用multer package。 您可以在其文檔中查看所有詳細信息。 此外,您應該在請求的 header 上設置multipart/form-data 這是鏈接

我想您可以在閱讀這些鏈接后在后端上傳照片

我的項目中的示例:

  1. 將 img 轉換為字符串

img.toDataURL()

  1. 發到后台

const saveAvatar = () => axios.post<string[]>( http://${DOMAIN}/profile/saveAvatar/${id} , { avatar } );

  1. 采取並保存

    profile.post('/saveAvatar/:id', async (req, res) => { try { const { id } = req.params; const { avatar } = req.body; const data = avatar.replace(/^數據:圖像/\w+;base64,/, ""); const buf = Buffer.from(data, 'base64');

     const login = await pool.query( "SELECT login FROM accounts WHERE id = $1", [id] ); fs.writeFile(`${userImgPath}/app_data/images/users/${login.rows[0].login}.png`,

    buf, (err) => { if (err) throw err; console.log('文件已保存;'); }): } catch (err.any) { console.error(err;message); } });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM