JSF + MySQL saveing Image

06/08/2020

0

Ola galera boa tarde. Bem vou direto ao ponto. Sou iniciante em java mas fiz um projeto para praticar e ate agora fiz tudo certo, porem nao estou conseguindo fazer o cadastro do produto, pretendo salvar a imagem em um diretorio e o caminho no banco, mas nao estou conseguindo com java parece mais complicado. Veja abaixo como esta meu projeto.
esta e minha clase java so com as declaracoes mas tem os gets and sets
   private int codProduct;
	private String category;
	private String name;
	private Integer quantity;
	private Double price;
	private String image;
	private String description;
	private String addeddate;
	private Providers providers = new Providers();



aqui my class Product_Dao, image comentei porque nao consegui fazer
    public void SaveProduct(Products prod) throws SQLException{
		StringBuilder sql = new StringBuilder();
		sql.append("INSERT INTO Products ");
		sql.append("(Category, Name, Quantity, Price, Image, Description, AddedDate, providers_codProvider )");
		sql.append("VALUE(?, ?, ?, ?, ?, ?, ?)");
		
		Connection conect = Connection_Db.conect();
		PreparedStatement comand = conect.prepareStatement(sql.toString());
		comand.setString(1, prod.getCategory());
		comand.setString(2,  prod.getName());
		comand.setInt(3, prod.getQuantity());
		comand.setDouble(4, prod.getPrice());
		//comand.setString(5, prod.getImage());
		comand.setString(5, prod.getDescription());
		comand.setString(6, prod.getAddeddate());
		comand.setInt(7, prod.getProviders().getCodProvider());
		comand.executeUpdate();
	}


Aqui my product_Bean to save the product.
    public void SaveProduct(){		
		if ((product.getProviders().getCodProvider() == 0)) {
			AlertMessages.Warning("You must select a Provider to add new Product!");
		}
		else if (product.getCategory().equals(null) || product.getName().equals(null) || product.getQuantity().equals(null) || 
				product.getPrice().equals(null)|| product.getQuantity() == 0 || product.getPrice() == 0) {
			AlertMessages.Fatal("Fields with (*) must be complete!!");
		}else{
			try {		
				Product_Dao prodDao = new Product_Dao();
				
				Date current_date = new Date();
				SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM/dd/YYYY hh:mm a");
				product.setAddeddate(dateFormat.format(current_date));
				prodDao.SaveProduct(product);
				
				//UPDATING THE LIST AFTER SAVE PRODUCT
				itens = prodDao.ListAllProducts();
				AlertMessages.Success(product.getName() + " added successfully");
				
			} catch (Exception e) {
				AlertMessages.Warning("Somenthing went wrong try again! ");
				e.printStackTrace();
			}
		}
	}


e aqui esta my form onde I get todas informacoes do product.
     <h:form id="frmAddProd" enctype="multipart/form-data">
	  			<div style="padding:8px 0 7px">
	  				<h:outputLabel style="color:#5B82FD" value="*Provider:" /><br />
	  				<p:selectOneMenu tabindex="1" style="width:96%; height:27px" filter="true" value="#{mbProduct.product.providers.codProvider}">
	  					<f:selectItem itemValue="" itemLabel="Select a Provider" />
	  					<f:selectItems value="#{mbProduct.comboProviders}" var="item" itemValue="#{item.codProvider}" itemLabel="#{item.name}" />
	  				</p:selectOneMenu>
	  			</div>
	  			
	  			<p:panelGrid columns="2" style="margin-top:12px;">
	  			
	  				<h:outputLabel style="color:#5B82FD" value="*Category:" />
	  				<h:outputLabel style="color:#5B82FD" value="*Name:" />
	  				
	  				<h:inputText size="16" maxlength="25" tabindex="2"
	  					requiredMessage="Category must be informed!" value="#{mbProduct.product.category}" />
	  				<h:inputText size="16" maxlength="25" tabindex="3" value="#{mbProduct.product.name}" />
	  			</p:panelGrid>
	  			
	  			<p:panelGrid columns="3" style="margin-top:12px;">
	  				<h:outputLabel style="color:#5B82FD" value="*Quantity:" />
	  				<h:outputLabel style="color:#5B82FD" value="*Price:" />
	  				<h:outputLabel style="color:#5B82FD" value="*Select Image" />
	  				
	  				<h:inputText size="8" maxlength="4" tabindex="4" value="#{mbProduct.product.quantity}" />
	  				<h:inputText size="8" maxlength="8" tabindex="5" value="#{mbProduct.product.price}" />
	  				<p:fileUpload  value="#" tabindex="6" mode="simple" skinSimple="true"/>
	  			</p:panelGrid>
		  		
	  			<div style="padding:8px 0">
	  				<h:outputLabel style="color:#5B82FD" value="Description:" /><br />
	  				<h:inputTextarea id="txDesc" style="width:97%; height:95px" maxlength="255" tabindex="7" value="#{mbProduct.product.description}" />
		  		</div>
		  			
	  			<span style="color:#black; font-size: 12px">Fields with (*) must be complete!</span>
	  			<p:separator />
	  			
	  			<div align="center">
	  				<p:commandButton value="SAVE" icon="ui-icon-folder-open" style="margin-right:14px; border: 1px solid #5B82FD" 
	  					tabindex="8" actionListener="#{mbProduct.SaveProduct}" oncomplete="PF(''diagNewProd'').hide();" 
	  					update=":frmproducts:tbproducts :msgGlobal" />
	  					
	  				<p:commandButton value="CANCEL" icon="ui-icon-close" tabindex="9" onclick="PF(''diagNewProd'').hide();" process="@this" 
	  					style="border: 1px solid #5B82FD" />
	  			</div>
	  		</h:form>


Por favor se alguem entendier melhor e puder ajudar agradeco, estou criando este projeto para praticar mas an image no consegui. I coloquei todas images com a padrao, poirque nao sei como cadastrar and recuperar para listar em cada products. Obrigadou a todous.
Celiol.

Celiol.

Responder

Posts

11/08/2020

Celiol.


Boa tarde. Bem vou direto ao ponto.
Sou iniciante em java, fiz um projeto para praticar. Tudo estava certo porem não estou conseguindo cadastrar a imagem, pretendo salvar a imagem em um file e o caminho no banco. Veja abaixo como esta meu projeto.

Classe Produto (gets e sets)
   private int codProduct;
	private String category;
	private String name;
	private Integer quantity;
	private Double price;
	private byte[] image;
	private String description;
	private String addeddate;
	private Providers providers = new Providers();



Classe Product_Dao.
    public void SaveProduct(Products prod) throws SQLException{
		StringBuilder sql = new StringBuilder();
		sql.append("INSERT INTO Products ");
		sql.append("(Category, Name, Quantity, Price, Image, Description, AddedDate, providers_codProvider )");
		sql.append("VALUE(?, ?, ?, ?, ?, ?, ?)");
		
		Connection conect = Connection_Db.conect();
		PreparedStatement comand = conect.prepareStatement(sql.toString());
		comand.setString(1, prod.getCategory());
		comand.setString(2,  prod.getName());
		comand.setInt(3, prod.getQuantity());
		comand.setDouble(4, prod.getPrice());

		comand.setBytes(5, prod.getImage());

		comand.setString(5, prod.getDescription());
		comand.setString(6, prod.getAddeddate());
		comand.setInt(7, prod.getProviders().getCodProvider());
		comand.executeUpdate();
	}


Aqui é a classe product_Bean para salvar os produtos.
    public void SaveProduct(){		
		if ((product.getProviders().getCodProvider() == 0)) {
			AlertMessages.Warning("You must select a Provider to add new Product!");
		}
		else if (product.getCategory().equals(null) || product.getName().equals(null) || product.getQuantity().equals(null) || 
				product.getPrice().equals(null)|| product.getQuantity() == 0 || product.getPrice() == 0) {
			AlertMessages.Fatal("Fields with (*) must be complete!!");
		}else{
			try {		
				Product_Dao prodDao = new Product_Dao();

                                byte[] fileByte = ByteConvertion(image.getInputStream());
				product.setImage(fileByte);
			
				prodDao.SaveProduct(product);
			} catch (Exception e) {
				AlertMessages.Warning("Somenthing went wrong try again! ");
				e.printStackTrace();
			}
		}
	}


Method para converter o upload para byte;
     public byte[] ByteConvertion(InputStream inputS) throws IOException{
		
		@SuppressWarnings("resource")
		ByteArrayOutputStream byteOutStr = new ByteArrayOutputStream();
		int reads = inputS.read();
		
		while (reads != -1) {
			byteOutStr.write(reads);
			reads = inputS.read();
		}
		return byteOutStr.toByteArray();
	}


Aqui esta meu form onde eu pego todas informacoes do product.
     <h:form id="frmAddProd" enctype="multipart/form-data">
	  			<p:panelGrid columns="3" style="margin-top:12px;">
	  				<h:outputLabel style="color:#5B82FD" value="*Select Image" />
	  				<p:fileUpload  value="#" tabindex="6" mode="simple" skinSimple="true"/>
	  			</p:panelGrid>
	  			
	  			<div align="center">
	  				<p:commandButton value="SAVE" icon="ui-icon-folder-open" style="margin-right:14px; border: 1px solid #5B82FD" 
	  					tabindex="8" actionListener="#{mbProduct.SaveProduct}" oncomplete="PF(''diagNewProd'').hide();" 
	  					update=":frmproducts:tbproducts :msgGlobal" />
	  			</div>
	  		</h:form>


Por favor, se alguém entender melhor e puder ajudar agradeço, estou criando este projeto para praticar mas a imagem não consegui. Coloquei images padrão por hora, pois ainda não sei como cadastrar e recuperar para listar em cada produto.

Fiz algumas mudanças de acordo com um exemplo para salvar imagem como byte no banco mas ainda esta dando erro e não consegui identificar o que é. Nesta linha:

byte[] fileByte = ByteConvertion(image.getInputStream());


quando tento salvar ele me da um erro "java.lang.NullPointerException" mas não sei porque pois eu seleciono o arquivo.
Responder

Assista grátis a nossa aula inaugural

Assitir aula

Saiba por que programar é uma questão de
sobrevivência e como aprender sem riscos

Assistir agora

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar