如何将png文件发送到node.js服务,并使用java、node.js和mysql将其存储在数据库中?

eqzww0vc  于 2021-07-12  发布在  Java
关注(0)|答案(0)|浏览(260)

我有一个java应用程序,我想发送一个png文件到node.js-api,它应该把图像保存在mysql数据库中。数据库表包含图像本身的id列和bigblob列。
java代码如下所示:

try (BufferedReader br = new BufferedReader(new FileReader("temp.png"))){
            StringBuilder content = new StringBuilder();
            String s = "";
            while((s = br.readLine()) != null)
                content.append(s);

            String url = postScreenshot(content.toString());

            return url;

}
catch (IOException e) {
}

对于请求,我使用的是apache httpclient:

public static String postScreenshot(String imageData) {
            String resAsString = Base64.getEncoder().encodeToString(imageData.getBytes());
            JSONObject jsonRequest = new JSONObject();
            jsonRequest.put("image", resAsString);

            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost request = new HttpPost("http://example.com/screenshots/send");
            StringEntity params = new StringEntity(jsonRequest.toString(), ContentType.APPLICATION_JSON);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);

            HttpResponse response = httpClient.execute(request);

            String responseString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            JSONObject jsonResult = new JSONObject(responseString);

            return "consumerURL";
}

尝试将接收到的图像保存到数据库的node.js代码如下所示:

router.post("/screenshots/send", (req, res) =>{
    let imageBinary = Buffer.from(req.body.image, "base64");

    let query = "INSERT INTO screenshots (image) VALUES (?)";
    query = mysql.format(query, [imageBinary]);
    con.query(query, (err, result) => {
        if (err) throw err;
        console.log("ID: ", result.insertId);
        res.send({
            id: result.insertId
        });
    });
});

我使用mysql npm包进行数据库连接。
node.js-service完成后,一条新记录将成功插入数据库。但是,当我尝试使用另一个节点服务获取保存的图像并尝试显示它或尝试从phpmyadmin下载文件时,该图片无法在浏览器中显示或在计算机上打开。
我做错什么了?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题