该应用程序是关于使用HTML从用户获取图像,通过API发送它,然后将其添加到数据库,将其保存为bytea
。
问题是我无法在需要时显示图像。
主页是我需要显示图像的地方。
axios.get('http://localhost:3333/api/getAllHairdressers').then((result)=>{
console.log(result.data);
this.setState({data:result.data})
})
}
log data.result是
counter:1 cutprice:null description:null id:32 image:{type: " Buffer",data:Array(438763)} location:null password:" 123" salname:null username:" ttt"
那么我怎么能显示这个图像? 我需要使用什么?
答案 0 :(得分:4)
Base64在从Postgres中检索时对其进行编码:
package de.java2enterprise.onlineshop;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public RegisterServlet() { }
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { }
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
final String email = request.getParameter("email");
final String password = request.getParameter("password");
final PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<body>");
out.println("<br> Ihre Eingaben");
out.println("<br> EMail: " + email);
out.println("<br> EMail: " + password);
out.println("</body>");
out.println("</html>");
out.close();
}
}
然后使用base64数据URL将其放入img标记:
SELECT ENCODE(byteaColumn,'base64') as base64 FROM...;
如果您无法修改数据库查询,可以在Javascript中对base64进行base64编码:
<img src={`data:image/jpeg;base64,${this.state.data}`} />
答案 1 :(得分:-1)
如果要在客户端处理转换:
使用base64字符串作为数据URI
<img src={`data:image/png;base64,${Buffer.from(this.state.data).toString('base64')}`} />
使用URL Web API中的URL.createObjectURL
创建一个src url
<img src={URL.createObjectURL(new Blob([Buffer.from(this.state.data)], {'type': 'image/png'}))} />
但是,后一种方法需要您通过调用URL.revokeObjectURL来释放与创建的url相关联的资源来进行清理。不过,当页面重新加载或关闭时,它将自动清除。