[英]Image upload Reactjs with Laravel PHP
我正在使用以下工具react-images-upload
import React, { useState } from "react";
import ImageUploader from "react-images-upload";
const App = () => {
const [image, setImage] = useState();
const handleSubmit = () => {
console.log(image[0]);
axios
.post(
"http://192.168.1.6:8001/api/upload",
{ image: image[0] },
{
headers: headers,
}
)
.then((response) => {
console.log(response);
});
};
return (
<div>
<ImageUploader
withIcon={true}
singleImage={true}
onChange={(p) => setImage(p.concat(p))}
imgExtension={[".jpg", ".gif", ".png", ".jpeg"]}
maxFileSize={4242880}
withPreview={true}
withIcon={true}
className="text-center"
/>
<button onClick={handleSubmit}>Upload</button>
</div>
);
};
export default App;
在 php 代碼中:-
public function upload(Request $request)
{
return response()->json($request->all());
}
在 php 中,$request->all() 的值未顯示在反應請求中發送的文件:-
將帶有文件/圖像的請求發送到 php 后端的正確方法是什么?
使用以下命令運行:
import React, { useState } from "react";
import ImageUploader from "react-images-upload";
const headers = {
Accept: "application/json", "Content-Type": "multipart/form-data; boundary=---------------------------974767299852498929531610575",
}
const App = () => {
const [image, setImage] = useState();
const handleSubmit = () => {
console.log(image[0]);
axios
.post(
"http://192.168.1.6:8001/api/upload",
{ image: image[0] },
{
headers: headers,
}
)
.then((response) => {
console.log(response);
});
};
return (
<div>
<ImageUploader
withIcon={true}
singleImage={true}
onChange={(p) => setImage(p.concat(p))}
imgExtension={[".jpg", ".gif", ".png", ".jpeg"]}
maxFileSize={4242880}
withPreview={true}
withIcon={true}
className="text-center"
/>
<button onClick={handleSubmit}>Upload</button>
</div>
);
};
export default App;
您實際上缺少標題“multipart/form-data”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.