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

reactjs-从服务器获取图像

(reactjs - Get the image from the server)

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

我使用axios post方法上传了一个图像文件,并且已成功将其上传到服务器...返回POST方法时,它返回的图像URL为:

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

现在,我想在屏幕上显示图像。如何获得该图像?我正在使用React.js来实现这一点。我用来发布图片的URL是: http://139.59.16.180:8269/player/details/${id}

我这样做是为了上传我的数据:

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))

我得到的答复是:

{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

我将为你提供一个示例,说明其如何在Node应用程序中完成,因为其基本概念与我不是Java开发人员的概念相同。

首先请注意,你的image_url / download_url应该保存如下,

https://yourdomain/folder/image_name

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

然后在Java Spring中需要一条路由,该路由确定要以哪种流形式将哪些图像发送到前端,如下所示,

 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
  });
});