見つかったオブジェクトのReactアプリを作成していて、ユーザーがこれらのオブジェクトの写真をアップロードできるようにしたい
axiosを使用したPOSTリクエストを介してマングースサーバーに画像を送信しようとしましたが、機能しません。
だからこれは私がプレビューでreactコンポーネントに画像を保存する方法です:
handleImage(event) {
let reader = new FileReader();
let file = event.target.files[0];
reader.onloadend = () => {
this.setState({
image: file,
imagePreviewUrl: reader.result
});
}
そしてこれは私がそれを送る方法です:
reader.readAsDataURL(file)
axios.post("/api/putData", {
id: idToBeAdded,
author : "TODO", //TODO
title: infos.title,
type: infos.type,
reward: this.state.reward,
description: infos.description,
image: infos.image,
});
これが反対側のリクエストを処理するための私のコードです:
router.post("/putData", (req, res) => {
let data = new Data();
const { id, author, title, type, reward, description, image } = req.body;
/*if ((!id && id !== 0) || !message) {
return res.json({
success: false,
error: "INVALID INPUTS"
});
}*/
data.title = title;
data.type = type;
data.reward = reward;
data.description = description;
data.author = author;
data.id = id;
data.image.data = image;
data.image.contentType = 'image/png'
data.save(err => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true });
});
});
したがって、この画像はフォームの一部であり、画像なしで送信すると、画像なしでDBに新しいドキュメントがあります(これは問題ありません)が、画像を読み込もうとすると、ドキュメントは作成されません。
私に何ができる ?
multipart / form-dataを処理するには、サーバーにmulterが必要です。画像を2つの方法で保存して、DBに保存する文字列に保存し、必要に応じてその文字列をデコードできます。または、画像をサーバーに保存し、そのURLをDBに保存することもできます。したがって、画像を使用する必要がある場合は、そのためのURLを使用できます。
サーバーに画像をアップロードするには、
import multer from 'multer'
var storage = multer.diskStorage({
destination: function (req, file, cb) {
var dirName =path.join(process.cwd(), './files/')
console.log(dirName)
if (!fs.existsSync(dirName)){
fs.mkdirSync(dirName);
}
cb(null,dirName)
}
},
filename: function (req, file, cb) {
cb(null, Date.now()+'-'+file.originalname)
}
})
var upload = multer({ storage: storage })
router.post("/putData",upload.single('files'), (req, res) => {
console.log(reqs.file.destination) // image url
console.log(JSON.parse(req.body)) // other things
})
フロントエンドに追加
handleSubmit(e){
var fd = new FormData()
fd.append('files',this.state.files[i][0],this.state.files[i][0].name)
var statebody = Object.assign({},this.state,{files:null})
fd.append('state',JSON.stringify(statebody))
axios.post('/api/',fd)
.then((res)=>{
console.log(res)
}).catch((e)=>{
console.log(e)
})
}
handleFiles(e){
this.setState({files:e.target.files})
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加