Boa tarde! gostaria de uma ajuda de como pegar o id da imagem que é feita o upload, no caso o upload vai certinho(consigo pegar o nome e o caminho da image), mas nao to conseguindo pegar o id da imagem ,no servlet sempre chega null, e nao sei como contornar , alguem poderia me ajudar de forma que junto com a imagem eu consiga enviar o id tbm ? desde já grato por qualquer ajuda que receba.
segue a parte que faz o upload com ajax:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<script src="js/javaScript.js"></script>
<title>Escolha a lá carte</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<style>
.action-icon{padding:5px;cursor:pointer;color:#fff}
.table{font-size:11px;}
.table>tbody>tr>td{padding: 2px 6px;vertical-align: middle;border:none;}
#main-container{padding: 0px 20px 40px; width: 50%;margin:auto;}
#upload-status-container{display:none;}
#nf,#cd{height:35px;width:100%;background-color: #323254;color: #fff;padding: 8px;border-top-left-radius: 10px;border-top-right-radius: 10px;}
#progress-bar-container{padding:20px;max-height:260px;overflow-y:auto;border:1px solid #323254;}
::-webkit-scrollbar {background-color: #fff; width: 8px; height: 8px;}
::-webkit-scrollbar-thumb {background-color: #C0C0C0; border-radius: 10px;}
</style>
</head>
<body>
<div id="main-container" >
<h3 class="text-info">Escolha os itens a baixo!</h3>
<hr>
<div style="margin-bottom: 20px" >
<fieldset></fieldset>
<table>
<tr>
<th>Img</th>
<th>Descrição</th>
<th>descricao</th>
</tr>
<c:forEach var="listar" items="${ListaRetornada}" varStatus="status">
<tr>
<td><label> <input type="file" name="files" id="file${listar.idCosmos}" multiple style="margin-bottom: 20px" />
<button class="btn btn-primary" id="btn" type="button" onclick="startUploading(${listar.idCosmos})" ><i class="fa fa-upload"></i> Upload file</button></label> </td>
<td><label for="${listar.idCosmos}"><input id="${listar.idCosmos}" type="checkbox" checked="checked" name="sku" value="${listar.idCosmos}"> ${listar.descricaoCosmos}</label> </td>
<td></td>
<c:out value="${item}"/>
</tr>
</c:forEach>
</table>
</div>
</div>
<script>
/* Globle variables */
var totalFileCount, fileUploadCount, fileSize,idprod;
/* comece a enviar arquivos */
function startUploading(idd) {
idprod=idd;
var files = document.getElementById("file"+idd).files;
if( files.length==0 || idd==null){
alert("Please choose at least one file and try.");
return;
}
fileUploadCount=0;
prepareProgressBarUI(files);
// upload através de chamada ajax
uploadFile(idd);
}
/* Este método será chamado para preparar a interface do usuário da barra de progresso */
function prepareProgressBarUI(files){
totalFileCount = files.length;
var $tbody=$("#progress-bar-container").find("tbody");
$tbody.empty();
$("#upload-header-text").html("1 of "+totalFileCount+" file(s) is uploading");
for(var i=0;i<totalFileCount;i++){
var fsize=parseFileSize(files[i].size);
var fname=files[i].name;
var bar='<tr id="progress-bar-'+i+'"><td style="width:75%"><div class="filename">'+fname+'</div>'
+'<div class="progress"><div class="progress-bar progress-bar-striped active" style="width:0%"></div></div></td>'
+'<td style="width:25%"><span class="size-loaded"></span> '+fsize+' <span class="percent-loaded"></span></td></tr>';
$tbody.append(bar);
}
$("#upload-status-container").show();
}
/*analise o tamanho do arquivo em kb/mb/gb */
function parseFileSize(size){
var precision=1;
var factor = Math.pow(10, precision);
size = Math.round(size / 1024); //size in KB
if(size < 1000){
return size+" KB";
}else{
size = Number.parseFloat(size / 1024); //size in MB
if(size < 1000){
return (Math.round(size * factor) / factor) + " MB";
}else{
size = Number.parseFloat(size / 1024); //size in GB
return (Math.round(size * factor) / factor) + " GB";
}
}
return 0;
}
/* um por um arquivo será carregado para o servidor por chamada ajax*/
function uploadFile(idd) {
var file = document.getElementById("file"+idd).files[fileUploadCount];
fileSize = file.size;
var xhr = new XMLHttpRequest();
var fd = new FormData();
fd.append("multipartFile", file);
xhr.upload.addEventListener("progress", onUploadProgress, false);
xhr.addEventListener("load", onUploadComplete, false);
xhr.addEventListener("error", onUploadError, false);
xhr.open("POST", "upimg");
xhr.send(fd);
}
/*Esta função irá atualizar continuamente a barra de progresso */
function onUploadProgress(e) {
if (e.lengthComputable) {
var percentComplete = parseInt((e.loaded) * 100 / fileSize);
var pbar = $('#progress-bar-'+fileUploadCount);
var bar=pbar.find(".progress-bar");
var sLoaded=pbar.find(".size-loaded");
var pLoaded=pbar.find(".percent-loaded");
bar.css("width",percentComplete + '%');
sLoaded.html(parseFileSize(e.loaded)+ " / ");
pLoaded.html("("+percentComplete+ "%)");
} else {
alert('unable to compute');
}
}
/* Esta função será chamada quando o upload for concluído */
function onUploadComplete(e, error) {
var pbar = $('#progress-bar-'+fileUploadCount);
if(error){
pbar.find(".progress-bar").removeClass("active").addClass("progress-bar-danger");
}else{
pbar.find(".progress-bar").removeClass("active");
pbar.find(".size-loaded").html('<i class="fa fa-check text-success"></i> ');
}
fileUploadCount++;
if (fileUploadCount < totalFileCount) {
//chamada ajax se houver mais arquivos
uploadFile(idprod);
$("#upload-header-text").html((fileUploadCount+1)+" of "+totalFileCount+" file(s) is uploading");
a(idprod);//aqui eu queria usar o ajax para enviar o id tbm da imagem por exemplo a pessoa selecionou 3 imagens no servlet imprimir o id 3x um para cada imagen
} else {
$("#upload-header-text").html("File(s) uploaded successfully!");
window.location.href='Estoque.jsp';
}
}
/* Esta função será chamada quando ocorrer um erro durante o upload */
function onUploadError(e) {
console.error("Something went wrong!");
onUploadComplete(e,true);
}
function showHide(ele){
if($(ele).hasClass('fa-window-minimize')){
$(ele).removeClass('fa-window-minimize').addClass('fa-window-restore').attr("title","restore");
$("#progress-bar-container").slideUp();
}else{
$(ele).addClass('fa-window-minimize').removeClass('fa-window-restore').attr("title","minimize");
$("#progress-bar-container").slideDown();
}
}
function a (idd){
$.ajax({
type: "POST",
dataType: 'text',
url: "upimg",
data: { id:idd}
}).done(function(data) {
console.log(data);
});
}
</script>
</body>
</html>
aqui o servlet:
package controle;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import javax.swing.JOptionPane;
/**
* Servlet implementation class UploadImg
*/
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50)
// 50MB
public class UploadImg extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UploadImg() {
super();
// TODO Auto-generated constructor stub
}
/**
* Nome do diretório onde os arquivos carregados serão salvos, relativo ao
* diretório de aplicativos da web.
*/
private static final String SAVE_DIR = "uploadFiles";
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// gets absolute path of the web application
String appPath = request.getServletContext().getRealPath("");
// constructs path of the directory to save uploaded file
String savePath = appPath + SAVE_DIR;
// creates the save directory if it does not exists
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
//String a=request.getParameter("nome");
String fileName = null;
for (Part part : request.getParts()) {
fileName = extractFileName(part);
part.write(savePath + File.separator + fileName);
}
// criamos uma variavel para armazenar o caminho e o nome do arquivo a
// ser processado
// String id = request.getParameter("sku");
String savePathFull = appPath + SAVE_DIR + File.separator + fileName;
System.out.println(savePathFull);
JOptionPane.showMessageDialog(null, request.getParameter("id")+"este é meu id");//
System.out.println(request.getParameter("id")+ "aaaaaaa");// aqui sempre é null
/*
* response.setContentType("text/plain"); // Set content type of the response so
* that jQuery knows what it can expect. response.setCharacterEncoding("UTF-8");
* // You want world domination, huh? response.getWriter().write(a); // Write
* response body.
*/ }
/**
* Extrai o nome do arquivo da disposição do conteúdo do cabeçalho HTTP
*/
private String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length() - 1);
}
}
return "";
}
}
a ideia é q a cada upload que o servlet receba eu armazene o caminho e i id , no momento só consigo guardar o caaminho e o nome do arquivo, se alguem poder me ajudar eu agradeço