英文:
How to send an image file from React.js to Spring Boot Rest API without using Axios?
问题
使用Springboot REST API和React.js保存图像的方法
我正在尝试创建一个React应用程序,并且我有一个Spring Boot Rest API。我已经创建了以下代码,它在POSTMAN中运行良好。我的问题是,我不知道如何从React将图像文件发送到我的API。请提供我完整的React代码部分。(我不想使用axios)
这是我的Springboot Rest API部分(这在没有任何问题的情况下运行)
@PostMapping("/uploadFile")
@CrossOrigin
public ResponseEntity<Object> fileUpload(@RequestParam("File") MultipartFile file) throws IOException{
File myfile = new File(FILE_DIRECTORY+file.getOriginalFilename());
myfile.createNewFile();
FileOutputStream fos = new FileOutputStream(myfile);
fos.write(file.getBytes());
FileName = file.getOriginalFilename();
fos.close();
return new ResponseEntity<Object>("Success.." + FileName, HttpStatus.OK);
}
这是我的React部分
import React, { useEffect, useState } from 'react';
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';
import Postview from '../componant/postview';
import Navigation from '../componant/navigation';
import Card from 'react-bootstrap/Card';
import '../pages/profile.css';
export default function Profile() {
var userId = sessionStorage.getItem("userID");
const [imgOne, setImgOne] = useState()
const [postBody, setPostBody] = useState()
const [postTitle, setPostTitle] = useState()
return (
<Container>
<Navigation /><br />
<Row>
<Col md="9">
<Postview />
</Col>
<Col md="3">
<Card >
<Card.Body >
<Form>
<Form.Group className="mb-3" controlId="exampleForm.ControlInput1">
<Form.Label>Images</Form.Label>
<Form.Control type="file" value={imgOne} onChange={(e) => setImgOne(e.target.value)} />
</Form.Group>
<Form.Group className="mb-3" controlId="exampleForm.ControlInput1">
<Form.Label>Title</Form.Label>
<Form.Control type="email" value={postTitle} onChange={(e) => setPostTitle(e.target.value)} />
</Form.Group>
<Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1">
<Form.Label>Description</Form.Label>
<Form.Control as="textarea" rows={3} value={postBody} onChange={(e) => setPostBody(e.target.value)} />
</Form.Group>
<Button id='postBtn' variant="primary">Post</Button>
</Form>
</Card.Body>
</Card>
</Col>
</Row>
</Container>
);
}
此外,我使用以下方式调用了一些API,它也起作用。 我想要一个像下面这样解决上述问题的代码
const registerClick = (e) => {
try {
let result = fetch('http://localhost:8080/user-save', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify({
"email": "" + email + "",
"name": "" + name + "",
"password": "" + password + "",
})
});
navigate('/');
} catch (e) {
console.log(e);
}
}
非常感谢!
英文:
How to save an Image using Springboot rest api and React.js
I am trying to make a react application and also I have a Spring boot Rest API. I have created following code and it is working well with POSTMAN. My problem is, I don't know how to send the image file from react to my api. Plese provide me the full react code part. (I don't want use axios)
This is my Springboot Rest API part (This is working without any problem)
@PostMapping("/uploadFile")
@CrossOrigin
public ResponseEntity<Object> fileUpload(@RequestParam("File") MultipartFile file) throws IOException{
File myfile = new File(FILE_DIRECTORY+file.getOriginalFilename());
myfile.createNewFile();
FileOutputStream fos = new FileOutputStream(myfile);
fos.write(file.getBytes());
FileName = file.getOriginalFilename();
fos.close();
return new ResponseEntity<Object>("Success.."+FileName,HttpStatus.OK);
}
This is my React part
import React, { useEffect, useState } from 'react';
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';
import Postview from '../componant/postview';
import Navigation from '../componant/navigation';
import Card from 'react-bootstrap/Card';
import '../pages/profile.css';
export default function Profile() {
var userId = sessionStorage.getItem("userID");
const [imgOne, setImgOne] = useState()
const [postBody, setPostBody] = useState()
const [postTitle, setPostTitle] = useState()
return (
<Container>
<Navigation /><br />
<Row>
<Col md="9">
<Postview />
</Col>
<Col md="3">
<Card >
<Card.Body >
<Form>
<Form.Group className="mb-3" controlId="exampleForm.ControlInput1">
<Form.Label>Images</Form.Label>
<Form.Control type="file" value={imgOne} onChange={(e) => setImgOne(e.target.value)} />
</Form.Group>
<Form.Group className="mb-3" controlId="exampleForm.ControlInput1">
<Form.Label>Title</Form.Label>
<Form.Control type="email" value={postTitle} onChange={(e) => setPostTitle(e.target.value)} />
</Form.Group>
<Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1">
<Form.Label>Description</Form.Label>
<Form.Control as="textarea" rows={3} value={postBody} onChange={(e) => setPostBody(e.target.value)} />
</Form.Group>
<Button id='postBtn' variant="primary">Post</Button>
</Form>
</Card.Body>
</Card>
</Col>
</Row>
</Container>
);
}
Also I have call some api using following way and it is also worked. I want a code for above problem just like below
const registerClick = (e) => {
try {
let result = fetch('http://localhost:8080/user-save', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify({
"email": "" + email + "",
"name": "" + name + "",
"password": "" + password + "",
})
});
navigate('/');
} catch (e) {
console.log(e);
}
}
Thank you very much
答案1
得分: 1
以下是翻译好的部分:
说明:
我创建了3个状态变量,只是查找表单更改。每当表单变得脏时,状态变量会捕获更改。提交按钮调用handleForm(e)
处理程序,将数据提交到运行在localhost
上端口8080
的Spring @RestController
React 实现:
import { useState } from "react";
export default function Form() {
const [title, setTitle] = useState("");
const [desc, setDesc] = useState("");
const [file, setFile] = useState("");
function handleForm(e) {
e.preventDefault();
const data = new FormData();
data.append("image", file);
data.append("title", title);
data.append("desc", desc);
fetch("http://localhost:8080/upload", {
method: "POST",
body: data,
});
}
function handleFileChange(e) {
if (e.target.files && e.target.files[0]) setFile(e.target.files[0]);
}
return (
<>
<form>
<input
type="text"
name="title"
placeholder="标题"
onKeyUp={(e) => setTitle(e.target.value)}
/>
<input
type="text"
name="description"
placeholder="描述"
onKeyUp={(e) => setDesc(e.target.value)}
/>
<input type="file" name="image" onChange={handleFileChange} />
<button type="submit" onClick={(e) => handleForm(e)}>
提交
</button>
</form>
</>
);
}
Spring-Boot 实现:
package com.springboot.learning.controllers;
import java.io.File;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class HomeController {
private static final String UPLOAD_PATH = "/home/user/eclipse-workspace/project-name/src/main/resources/static/images/";
@PostMapping("/upload")
@CrossOrigin
public ResponseEntity<String> handleFileUpload(@RequestParam("image") MultipartFile file,
@RequestParam String title, @RequestParam String desc) {
String fileName = file.getOriginalFilename();
System.out.println(title);
System.out.println(desc);
System.out.println(fileName);
try {
file.transferTo(new File(UPLOAD_PATH + fileName));
return ResponseEntity.ok("文件上传成功。");
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
}
附注:如果项目中不存在resources/static/images
文件夹,您可能需要创建它。
英文:
The following code snippets for React
and Sprint-Boot
should be enough to get you started.
Explaination:
I've created 3 state variables that simply look for form changes. Whenever the form gets dirty, the state variables capture the changes. The submit button calls the handleForm(e)
handler that submits the data to your spring @RestController
which runs on localhost
with port 8080
React implementation:
import { useState } from "react";
export default function Form() {
const [title, setTitle] = useState("");
const [desc, setDesc] = useState("");
const [file, setFile] = useState("");
function handleForm(e) {
e.preventDefault();
const data = new FormData();
data.append("image", file);
data.append("title", title);
data.append("desc", desc);
fetch("http://localhost:8080/upload", {
method: "POST",
body: data,
});
}
function handleFileChange(e) {
if (e.target.files && e.target.files[0]) setFile(e.target.files[0]);
}
return (
<>
<form>
<input
type="text"
name="title"
placeholder="title"
onKeyUp={(e) => setTitle(e.target.value)}
/>
<input
type="text"
name="description"
placeholder="description"
onKeyUp={(e) => setDesc(e.target.value)}
/>
<input type="file" name="image" onChange={handleFileChange} />
<button type="submit" onClick={(e) => handleForm(e)}>
Submit
</button>
</form>
</>
);
}
Spring-Boot implementation
package com.springboot.learning.controllers;
import java.io.File;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class HomeController {
private static final String UPLOAD_PATH = "/home/user/eclipse-workspace/project-name/src/main/resources/static/images/";
@PostMapping("/upload")
@CrossOrigin
public ResponseEntity<String> handleFileUpload(@RequestParam("image") MultipartFile file,
@RequestParam String title, @RequestParam String desc) {
String fileName = file.getOriginalFilename();
System.out.println(title);
System.out.println(desc);
System.out.println(fileName);
try {
file.transferTo(new File(UPLOAD_PATH + fileName));
return ResponseEntity.ok("File uploaded successfully.");
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
}
P.S: You may need to create the folder resources/static/images
in your project if not already existing.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论