Warm tip: This article is reproduced from serverfault.com, please click

Get the image from the server

发布于 2020-11-28 09:44:06

I uploaded an image file using axios post method and it was successfully uploaded to the server... On return to the POST method, it returned the Image URL as:

{imageUrl: "/root/TTAppJava/images/players/Screenshot from 2020-11-24 16-38-57.png"}

Now, I want to display the image onto my screen. How can I get that image? I am using React.js to implement this. The URL I used to post the image is: http://139.59.16.180:8269/player/details/${id}

I am doing this to upload my data:

var formData = new FormData()
    formData.append("file", image);
    const theWrapper = {
        "data": {
            "name": name,
            "age": age,
            "email": email,
            "gender": gender
        }
    }

    formData.append("theWrapper", JSON.stringify(theWrapper))

    Axios.post("http://139.59.16.180:8269/player/add",
        formData,
        { headers: { Authorization: "Bearer " + localStorage.getItem("token") } }
    ).then(res => {
        console.log(res)
        alert("Player added successfully.")
        history.push("/players")
    })
        .catch(err => alert(err.messge))

And the response I am getting is:

{id: 14, name: "shreyas", email: "asdfjka@gmail.com", gender: "Male", imageUrl: "/root/TTAppJava/images/players/Screenshot from 2020-11-24 16-38-57.png", …}
Questioner
Shreyas Jain
Viewed
0
Alish Giri 2020-11-28 21:33:07

I will give you an example how its done in Node app, since the underlying concept will be the same as I am not a Java developer.

First please note your image_url/download_url should be saved as follows,

https://yourdomain/folder/image_name

example: http://localhost:3000/uploads_folder/my_image_name.jpg

and then you need a route in Java Spring which figures out what image to send to the front-end as Stream like below,

 router.get("/:folder/:image_name", async (req, res) => {
  const { folder, image_name } = req.params;

  // find an image based on the downloadUrl in the folder where files are saved.
  // Please note, after uploading file successfully generate a download url 
  // appropriately so that this route can help figure out which image you 
  // are looking for.
  const file = path.join(`path/to/${folder}`, `${image_name}`);

  // Figure out a way how stream works in your context.
  // Providing MIME type is important!
  const type = mime[path.extname(file).slice(1)] || "image/jpg";
  const s = fs.createReadStream(file);
  s.on("open", () => {
    res.set("Content-Type", type);
    s.pipe(res);
  });
  s.on("error", (err) => {
    // Handle Error
  });
});