如何在不使用Axios的情况下,从React.js发送图像文件到Spring Boot Rest API?

huangapple go评论72阅读模式
英文:

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(&quot;/uploadFile&quot;)
@CrossOrigin
public ResponseEntity&lt;Object&gt; fileUpload(@RequestParam(&quot;File&quot;) 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&lt;Object&gt;(&quot;Success..&quot;+FileName,HttpStatus.OK);
} 

This is my React part

import React, { useEffect, useState } from &#39;react&#39;;
import Container from &#39;react-bootstrap/Container&#39;;
import Row from &#39;react-bootstrap/Row&#39;;
import Col from &#39;react-bootstrap/Col&#39;;
import Form from &#39;react-bootstrap/Form&#39;;
import Button from &#39;react-bootstrap/Button&#39;;
import Postview from &#39;../componant/postview&#39;;
import Navigation from &#39;../componant/navigation&#39;;
import Card from &#39;react-bootstrap/Card&#39;;
import &#39;../pages/profile.css&#39;;
export default function Profile() {
var userId = sessionStorage.getItem(&quot;userID&quot;);
const [imgOne, setImgOne] = useState()
const [postBody, setPostBody] = useState()
const [postTitle, setPostTitle] = useState()
return (
&lt;Container&gt;
&lt;Navigation /&gt;&lt;br /&gt;
&lt;Row&gt;
&lt;Col md=&quot;9&quot;&gt;
&lt;Postview /&gt;
&lt;/Col&gt;
&lt;Col md=&quot;3&quot;&gt;
&lt;Card &gt;
&lt;Card.Body &gt;
&lt;Form&gt;
&lt;Form.Group className=&quot;mb-3&quot; controlId=&quot;exampleForm.ControlInput1&quot;&gt;
&lt;Form.Label&gt;Images&lt;/Form.Label&gt;
&lt;Form.Control type=&quot;file&quot; value={imgOne} onChange={(e) =&gt; setImgOne(e.target.value)} /&gt;
&lt;/Form.Group&gt;
&lt;Form.Group className=&quot;mb-3&quot; controlId=&quot;exampleForm.ControlInput1&quot;&gt;
&lt;Form.Label&gt;Title&lt;/Form.Label&gt;
&lt;Form.Control type=&quot;email&quot; value={postTitle} onChange={(e) =&gt; setPostTitle(e.target.value)} /&gt;
&lt;/Form.Group&gt;
&lt;Form.Group className=&quot;mb-3&quot; controlId=&quot;exampleForm.ControlTextarea1&quot;&gt;
&lt;Form.Label&gt;Description&lt;/Form.Label&gt;
&lt;Form.Control as=&quot;textarea&quot; rows={3} value={postBody} onChange={(e) =&gt; setPostBody(e.target.value)} /&gt;
&lt;/Form.Group&gt;
&lt;Button id=&#39;postBtn&#39; variant=&quot;primary&quot;&gt;Post&lt;/Button&gt;
&lt;/Form&gt;
&lt;/Card.Body&gt;
&lt;/Card&gt;
&lt;/Col&gt;
&lt;/Row&gt;
&lt;/Container&gt;
);
}

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) =&gt; {
try {
let result = fetch(&#39;http://localhost:8080/user-save&#39;, {
method: &#39;post&#39;,
headers: {
&#39;Accept&#39;: &#39;application/json&#39;,
&#39;Content-type&#39;: &#39;application/json&#39;,
},
body: JSON.stringify({
&quot;email&quot;: &quot;&quot; + email + &quot;&quot;,
&quot;name&quot;: &quot;&quot; + name + &quot;&quot;,
&quot;password&quot;: &quot;&quot; + password + &quot;&quot;,
})
});
navigate(&#39;/&#39;);
} 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 &quot;react&quot;;

export default function Form() {
  const [title, setTitle] = useState(&quot;&quot;);
  const [desc, setDesc] = useState(&quot;&quot;);
  const [file, setFile] = useState(&quot;&quot;);

  function handleForm(e) {
    e.preventDefault();

    const data = new FormData();
    data.append(&quot;image&quot;, file);
    data.append(&quot;title&quot;, title);
    data.append(&quot;desc&quot;, desc);

    fetch(&quot;http://localhost:8080/upload&quot;, {
      method: &quot;POST&quot;,
      body: data,
    });
  }

  function handleFileChange(e) {
    if (e.target.files &amp;&amp; e.target.files[0]) setFile(e.target.files[0]);
  }

  return (
    &lt;&gt;
      &lt;form&gt;
        &lt;input
          type=&quot;text&quot;
          name=&quot;title&quot;
          placeholder=&quot;title&quot;
          onKeyUp={(e) =&gt; setTitle(e.target.value)}
        /&gt;
        &lt;input
          type=&quot;text&quot;
          name=&quot;description&quot;
          placeholder=&quot;description&quot;
          onKeyUp={(e) =&gt; setDesc(e.target.value)}
        /&gt;
        &lt;input type=&quot;file&quot; name=&quot;image&quot; onChange={handleFileChange} /&gt;
        &lt;button type=&quot;submit&quot; onClick={(e) =&gt; handleForm(e)}&gt;
          Submit
        &lt;/button&gt;
      &lt;/form&gt;
    &lt;/&gt;
  );
}
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 = &quot;/home/user/eclipse-workspace/project-name/src/main/resources/static/images/&quot;;

	@PostMapping(&quot;/upload&quot;)
	@CrossOrigin
	public ResponseEntity&lt;String&gt; handleFileUpload(@RequestParam(&quot;image&quot;) 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(&quot;File uploaded successfully.&quot;);
		} 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.

huangapple
  • 本文由 发表于 2023年5月21日 14:22:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76298557.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定