Opa Ewerton see if it helps you:
In the image above I register a product, simulating an online toy store.
In this other image above, I upload the image to save in the database.
The Final Result, which appears when I do a search by clicking on the category where the product was registered. I saved the image using Blob type in Mysqlserver.
In that case I’m using the JSP instead of JSF.
public class ServletUpload extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
@SuppressWarnings("rawtypes")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
if (isMultiPart) {
System.out.println("Upload Imagem");
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
String usuario ="";
String titulo = "";
String descricao = "";
byte[] imagem = null;
try {
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if(item.getFieldName().equals("user")){
usuario = item.getString();
System.out.println(usuario);}
if (item.getFieldName().equals("titulo")){
titulo= item.getString();
System.out.println(titulo);}
if(item.getFieldName().equals("descricao")){
descricao = item.getString();
System.out.println(descricao);}
if (item.getFieldName().equals("file"))
imagem = read(item); //Chamo método para converter a imagem
if (!item.isFormField()) {
if (item.getName().length() > 0) {
System.out.println("chama método");
Imagem img = new Imagem();
img.setTitulo(titulo);
img.setDescricao(descricao);
img.setImagem(imagem);
ImagemDAO dao = new ImagemDAO();
dao.gravar(img);
HttpSession session = request.getSession(true);
session.setAttribute("user", usuario);
response.sendRedirect("/LojaBrinquedos/Paginas/Admin/Alertas/Imagem/imgSalva.jsp");
}
}
}
} catch (FileUploadException ex) {
ex.printStackTrace();
System.out.println("Upload Failed");
response.sendRedirect("/LojaBrinquedos/Paginas/Admin/Alertas/Imagem/imgError.jsp");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
private byte[] read(FileItem fi) throws IOException{
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream is = fi.getInputStream();
int read = 0;
final byte[] b = new byte[1024];
while ((read = is.read(b)) != -1) {
out.write(b, 0, read);
}
return out.toByteArray();
}
}
The image above is mine Servletupload (controller), where I get the data of the fields who are on the image upload page.
The method read I use to convert the image to type Blob before saving to the database, remembering that it is present in the execution of the Servletupload.
In the database to save you will need to do as described below:
ps.setBytes(3, img.getImagem());
It shouldn’t be complicated to do this process for JSF using a Managedbean.
I hope I’ve helped you, any writing there.
Hugs.