List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent
public static final boolean isMultipartContent(HttpServletRequest request)
From source file:jp.co.opentone.bsol.linkbinder.view.filter.UploadFileFilter.java
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { // ????/*from w w w. j a va2 s.c om*/ if (!(req instanceof HttpServletRequest)) { chain.doFilter(req, res); return; } HttpServletRequest httpReq = (HttpServletRequest) req; // ?????????? if (!ServletFileUpload.isMultipartContent(httpReq)) { chain.doFilter(req, res); return; } DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(factory); factory.setSizeThreshold(thresholdSize); sfu.setSizeMax(maxSize); // sfu.setHeaderEncoding(req.getCharacterEncoding()); try { @SuppressWarnings("unchecked") Iterator<FileItem> ite = sfu.parseRequest(httpReq).iterator(); List<String> keys = new ArrayList<String>(); List<String> names = new ArrayList<String>(); List<String> fieldNames = new ArrayList<String>(); List<Long> fileSize = new ArrayList<Long>(); while (ite.hasNext()) { String name = null; FileItem item = ite.next(); // ???? if (!(item.isFormField())) { name = item.getName(); name = name.substring(name.lastIndexOf('\\') + 1); if (StringUtils.isEmpty(name)) { continue; } File f = null; // CHECKSTYLE:OFF // ??????????. while ((f = new File(createTempFilePath())).exists()) { } // CHECKSTYLE:ON if (!validateByteLength(name, maxFilenameLength, minFilenameLength)) { // ???? names.add(name); keys.add(UploadedFile.KEY_FILENAME_OVER); fieldNames.add(item.getFieldName()); fileSize.add(item.getSize()); } else if (item.getSize() == 0) { // 0 names.add(name); keys.add(UploadedFile.KEY_SIZE_ZERO); fieldNames.add(item.getFieldName()); fileSize.add(item.getSize()); } else if (maxFileSize > 0 && item.getSize() > maxFileSize) { // ? // ?0??????Validation names.add(name); keys.add(UploadedFile.KEY_SIZE_OVER); fieldNames.add(item.getFieldName()); fileSize.add(item.getSize()); } else { item.write(f); names.add(name); keys.add(f.getName()); fieldNames.add(item.getFieldName()); fileSize.add(item.getSize()); } f.deleteOnExit(); } } // UploadFileFilterResult result = new UploadFileFilterResult(); result.setResult(UploadFileFilterResult.RESULT_OK); result.setNames(names.toArray(new String[names.size()])); result.setKeys(keys.toArray(new String[keys.size()])); result.setFieldNames(fieldNames.toArray(new String[fieldNames.size()])); result.setFileSize(fileSize.toArray(new Long[fileSize.size()])); writeResponse(req, res, result); } catch (Exception e) { e.printStackTrace(); // UploadFileFilterResult result = new UploadFileFilterResult(); result.setResult(UploadFileFilterResult.RESULT_NG); writeResponse(req, res, result); } }
From source file:application.controllers.admin.EditEmotion.java
private String uploadNewImage(HttpServletRequest request, HttpServletResponse response) { String linkImage = emotionSelected.linkImage; if (!ServletFileUpload.isMultipartContent(request)) { return ""; }/*from w w w . jav a 2s . c o m*/ // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(UploadConstant.THRESHOLD_SIZE); // Location to save data that is larger than maxMemSize. factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setFileSizeMax(UploadConstant.MAX_FILE_SIZE); upload.setSizeMax(UploadConstant.MAX_REQUEST_SIZE); // constructs the directory path to store upload file //groupEmotionId chinh la folder chua // creates the directory if it does not exist String[] arrLink = emotionSelected.linkImage.split("/"); if (arrLink.length < 3) { return ""; } try { List formItems = upload.parseRequest(request); Iterator iter = formItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // processes only fields that are not form fields if (item.isFormField()) { //form field if (item.getFieldName().equals("groupEmotion")) { try { if (emotionSelected.groupEmotionId != Integer.parseInt(item.getString())) { //thay doi group id --> chuyen file sang folder tuong ung va thay doi imagelink //chuyen file sang folder tuong ung theo group da chon String sourcePath = Registry.get("imageHost") + emotionSelected.linkImage; //item.getString --> groupEmotion chon String desPath = Registry.get("imageHost") + "/emotions-image/" + item.getString() + "/" + arrLink[3]; File sourceDir = new File(sourcePath); File desDir = new File(desPath); if (sourceDir.exists()) { FileUtils.copyFile(sourceDir, desDir); sourceDir.delete(); } emotionSelected.groupEmotionId = Integer.parseInt(item.getString()); linkImage = "/emotions-image/" + emotionSelected.groupEmotionId + "/" + arrLink[3]; } } catch (NumberFormatException ex) { ex.printStackTrace(); } } if (item.getFieldName().equals("description")) { emotionSelected.description = item.getString(); } if (item.getFieldName().equals("imageURL")) { emotionSelected.linkImage = item.getString(); } } else { String fileName = new File(item.getName()).getName(); //file name bang empty khi ko upload new image if ("".equals(fileName)) { continue; } String filePath = Registry.get("imageHost") + emotionSelected.linkImage; File newImage = new File(filePath); File oldImage = new File(filePath); // xoa image cu bi edit if (oldImage.exists()) { oldImage.delete(); } // save image moi vao folder cua group id va cung ten moi image cu item.write(newImage); //save lai file cua image moi linkImage = "/emotions-image/" + emotionSelected.groupEmotionId + "/" + arrLink[3]; } } } catch (Exception ex) { Logger.getLogger(EditEmotion.class.getName()).log(Level.SEVERE, null, ex); } return linkImage; }
From source file:com.ikon.servlet.admin.CronTabServlet.java
@Override @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doPost({}, {})", request, response); request.setCharacterEncoding("UTF-8"); String action = ""; String userId = request.getRemoteUser(); updateSessionManager(request);//w ww . j a v a 2 s .c o m try { if (ServletFileUpload.isMultipartContent(request)) { InputStream is = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); CronTab ct = new CronTab(); for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("action")) { action = item.getString("UTF-8"); } else if (item.getFieldName().equals("ct_id")) { ct.setId(Integer.parseInt(item.getString("UTF-8"))); } else if (item.getFieldName().equals("ct_name")) { ct.setName(item.getString("UTF-8")); } else if (item.getFieldName().equals("ct_mail")) { ct.setMail(item.getString("UTF-8")); } else if (item.getFieldName().equals("ct_expression")) { ct.setExpression(item.getString("UTF-8")); } else if (item.getFieldName().equals("ct_active")) { ct.setActive(true); } } else { is = item.getInputStream(); ct.setFileName(FilenameUtils.getName(item.getName())); ct.setFileContent(SecureStore.b64Encode(IOUtils.toByteArray(is))); ct.setFileMime(MimeTypeConfig.mimeTypes.getContentType(item.getName())); is.close(); } } if (action.equals("create")) { CronTabDAO.create(ct); // Activity log UserActivity.log(userId, "ADMIN_CRONTAB_CREATE", null, null, ct.toString()); list(request, response); } else if (action.equals("edit")) { CronTabDAO.update(ct); // Activity log UserActivity.log(userId, "ADMIN_CRONTAB_EDIT", Long.toString(ct.getId()), null, ct.toString()); list(request, response); } else if (action.equals("delete")) { CronTabDAO.delete(ct.getId()); // Activity log UserActivity.log(userId, "ADMIN_CRONTAB_DELETE", Long.toString(ct.getId()), null, null); list(request, response); } } } catch (DatabaseException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (FileUploadException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } }
From source file:com.openkm.servlet.admin.DatabaseQueryServlet.java
@Override @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doPost({}, {})", request, response); request.setCharacterEncoding("UTF-8"); updateSessionManager(request);/*from w w w . j ava 2s . c o m*/ String user = request.getRemoteUser(); ServletContext sc = getServletContext(); Session session = null; try { if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); boolean showSql = false; String vtable = ""; String type = ""; String qs = ""; byte[] data = null; for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("qs")) { qs = item.getString("UTF-8"); } else if (item.getFieldName().equals("type")) { type = item.getString("UTF-8"); } else if (item.getFieldName().equals("showSql")) { showSql = true; } else if (item.getFieldName().equals("vtables")) { vtable = item.getString("UTF-8"); } } else { data = item.get(); } } if (!qs.equals("") && !type.equals("")) { session = HibernateUtil.getSessionFactory().openSession(); sc.setAttribute("qs", qs); sc.setAttribute("type", type); if (type.equals("jdbc")) { executeJdbc(session, qs, sc, request, response); // Activity log UserActivity.log(user, "ADMIN_DATABASE_QUERY_JDBC", null, null, qs); } else if (type.equals("hibernate")) { executeHibernate(session, qs, showSql, sc, request, response); // Activity log UserActivity.log(user, "ADMIN_DATABASE_QUERY_HIBERNATE", null, null, qs); } else if (type.equals("metadata")) { sc.setAttribute("vtable", vtable); executeMetadata(session, qs, false, sc, request, response); // Activity log UserActivity.log(user, "ADMIN_DATABASE_QUERY_METADATA", null, null, qs); } } else if (data != null && data.length > 0) { sc.setAttribute("exception", null); session = HibernateUtil.getSessionFactory().openSession(); executeUpdate(session, data, sc, request, response); // Activity log UserActivity.log(user, "ADMIN_DATABASE_QUERY_FILE", null, null, new String(data)); } else { sc.setAttribute("qs", qs); sc.setAttribute("type", type); sc.setAttribute("showSql", showSql); sc.setAttribute("exception", null); sc.setAttribute("globalResults", new ArrayList<DbQueryGlobalResult>()); sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response); } } else { // Edit table cell value String action = request.getParameter("action"); String vtable = request.getParameter("vtable"); String column = request.getParameter("column"); String value = request.getParameter("value"); String id = request.getParameter("id"); if (action.equals("edit")) { int idx = column.indexOf('('); if (idx > 0) { column = column.substring(idx + 1, idx + 6); } String hql = "update DatabaseMetadataValue dmv set dmv." + column + "='" + value + "' where dmv.table='" + vtable + "' and dmv.id=" + id; log.info("HQL: {}", hql); session = HibernateUtil.getSessionFactory().openSession(); int rows = session.createQuery(hql).executeUpdate(); log.info("Rows affected: {}", rows); } } } catch (FileUploadException e) { sendError(sc, request, response, e); } catch (SQLException e) { sendError(sc, request, response, e); } catch (HibernateException e) { sendError(sc, request, response, e); } catch (DatabaseException e) { sendError(sc, request, response, e); } catch (IllegalAccessException e) { sendError(sc, request, response, e); } catch (InvocationTargetException e) { sendError(sc, request, response, e); } catch (NoSuchMethodException e) { sendError(sc, request, response, e); } finally { HibernateUtil.close(session); } }
From source file:com.ephesoft.gxt.systemconfig.server.ImportPluginUploadServlet.java
private void attachFile(HttpServletRequest req, HttpServletResponse resp, BatchSchemaService batchSchemaService) throws IOException { String errorMessageString = EMPTY_STRING; PrintWriter printWriter = resp.getWriter(); File tempZipFile = null;//from ww w .j av a 2s . c o m InputStream instream = null; OutputStream out = null; ZipInputStream zipInputStream = null; List<ZipEntry> zipEntries = null; if (ServletFileUpload.isMultipartContent(req)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); String exportSerailizationFolderPath = EMPTY_STRING; try { Properties allProperties = ApplicationConfigProperties.getApplicationConfigProperties() .getAllProperties(META_INF_APPLICATION_PROPERTIES); exportSerailizationFolderPath = allProperties.getProperty(PLUGIN_UPLOAD_PROPERTY_NAME); } catch (IOException e) { } File exportSerailizationFolder = new File(exportSerailizationFolderPath); if (!exportSerailizationFolder.exists()) { exportSerailizationFolder.mkdir(); } List<FileItem> items; try { items = upload.parseRequest(req); for (FileItem item : items) { if (!item.isFormField()) { zipFileName = item.getName(); if (zipFileName != null) { zipFileName = zipFileName.substring(zipFileName.lastIndexOf(File.separator) + 1); } zipPathname = exportSerailizationFolderPath + File.separator + zipFileName; try { instream = item.getInputStream(); tempZipFile = new File(zipPathname); if (tempZipFile.exists()) { tempZipFile.delete(); } out = new FileOutputStream(tempZipFile); byte buf[] = new byte[1024]; int len; while ((len = instream.read(buf)) > 0) { out.write(buf, 0, len); } } catch (FileNotFoundException e) { log.error("Unable to create the export folder." + e, e); printWriter.write("Unable to create the export folder.Please try again."); } catch (IOException e) { log.error("Unable to read the file." + e, e); printWriter.write("Unable to read the file.Please try again."); } finally { if (out != null) { try { out.close(); } catch (IOException ioe) { log.info("Could not close stream for file." + tempZipFile); } } if (instream != null) { try { instream.close(); } catch (IOException ioe) { log.info("Could not close stream for file." + zipFileName); } } } } } } catch (FileUploadException e) { log.error("Unable to read the form contents." + e, e); printWriter.write("Unable to read the form contents.Please try again."); } // Unnecessary code to unzip the attached file removed. zipInputStream = new ZipInputStream(new FileInputStream(zipPathname)); zipEntries = new ArrayList<ZipEntry>(); ZipEntry nextEntry = zipInputStream.getNextEntry(); while (nextEntry != null) { zipEntries.add(nextEntry); nextEntry = zipInputStream.getNextEntry(); } errorMessageString = processZipFileContents(zipEntries, zipPathname); } else { log.error("Request contents type is not supported."); printWriter.write("Request contents type is not supported."); } // Temp file is now not created. if (validZipContent) { String zipFileNameWithoutExtension = zipPathname.substring(0, zipPathname.lastIndexOf('.')); printWriter.write(SystemConfigConstants.PLUGIN_NAME + zipFileNameWithoutExtension); printWriter.append(RESULT_SEPERATOR); printWriter.append(SystemConfigConstants.JAR_FILE_PATH).append(jarFilePath); printWriter.append(RESULT_SEPERATOR); printWriter.append(SystemConfigConstants.XML_FILE_PATH).append(xmlFilePath); printWriter.append(RESULT_SEPERATOR); printWriter.flush(); } else { printWriter.write("Error while importing.Please try again." + CAUSE + errorMessageString); } }
From source file:de.mpg.mpdl.service.rest.screenshot.service.HtmlScreenshotServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {// w w w . j a v a 2 s.co m if (ServletFileUpload.isMultipartContent(req)) { file = screenshotService.takeScreenshot(getUploadedFiles(req)); } else { File html = File.createTempFile("htmlScreenshot", ".html"); if (req.getParameter("html") != null) { IOUtils.write(req.getParameter("html").getBytes(), new FileOutputStream(html)); } else { IOUtils.copy(req.getInputStream(), new FileOutputStream(html)); } System.out.println(html.getAbsolutePath()); // TO Do After the copy the of the files browserWidth = (readBrowserParam(req, "browserWidth") != "") ? Integer.parseInt(req.getParameter("browserWidth")) : HtmlScreenshotService.DEFAULT_WIDTH; browserHeight = (readBrowserParam(req, "browserHeight") != "") ? Integer.parseInt(req.getParameter("browserHeight")) : HtmlScreenshotService.DEFAULT_HEIGHT; useFireFox = (readBrowserParam(req, "useFireFox") != "") ? Boolean.parseBoolean(req.getParameter("useFireFox")) : false; file = screenshotService.takeScreenshot(html, browserWidth, browserHeight, useFireFox); if (transformScreenshot(req)) { imageTransformer.transform(file, resp.getOutputStream(), readParam(req, "format"), readParam(req, "size"), readParam(req, "crop"), readParam(req, "priority"), readParam(req, "params1"), readParam(req, "params2")); } else IOUtils.copy(new FileInputStream(file), resp.getOutputStream()); } } catch (Exception e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); e.printStackTrace(); } }
From source file:com.ikon.servlet.admin.ConfigServlet.java
@Override @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doPost({}, {})", request, response); request.setCharacterEncoding("UTF-8"); ServletContext sc = getServletContext(); String action = null;// w w w.j a v a 2 s . co m String filter = null; String userId = request.getRemoteUser(); Session dbSession = null; updateSessionManager(request); try { if (ServletFileUpload.isMultipartContent(request)) { InputStream is = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Config cfg = new Config(); byte data[] = null; for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("action")) { action = item.getString("UTF-8"); } else if (item.getFieldName().equals("filter")) { filter = item.getString("UTF-8"); } else if (item.getFieldName().equals("cfg_key")) { cfg.setKey(item.getString("UTF-8")); } else if (item.getFieldName().equals("cfg_type")) { cfg.setType(item.getString("UTF-8")); } else if (item.getFieldName().equals("cfg_value")) { cfg.setValue(item.getString("UTF-8").trim()); } } else { is = item.getInputStream(); data = IOUtils.toByteArray(is); is.close(); } } if (action.equals("create")) { if (Config.BOOLEAN.equals(cfg.getType())) { cfg.setValue(Boolean.toString(cfg.getValue() != null && !cfg.getValue().equals(""))); } else if (Config.SELECT.equals(cfg.getType())) { ConfigStoredSelect stSelect = ConfigDAO.getSelect(cfg.getKey()); if (stSelect != null) { for (ConfigStoredOption stOption : stSelect.getOptions()) { if (stOption.getValue().equals(cfg.getValue())) { stOption.setSelected(true); } } } cfg.setValue(new Gson().toJson(stSelect)); } ConfigDAO.create(cfg); com.ikon.core.Config.reload(sc, new Properties()); // Activity log UserActivity.log(userId, "ADMIN_CONFIG_CREATE", cfg.getKey(), null, cfg.toString()); list(userId, filter, request, response); } else if (action.equals("edit")) { if (Config.BOOLEAN.equals(cfg.getType())) { cfg.setValue(Boolean.toString(cfg.getValue() != null && !cfg.getValue().equals(""))); } else if (Config.SELECT.equals(cfg.getType())) { ConfigStoredSelect stSelect = ConfigDAO.getSelect(cfg.getKey()); if (stSelect != null) { for (ConfigStoredOption stOption : stSelect.getOptions()) { if (stOption.getValue().equals(cfg.getValue())) { stOption.setSelected(true); } else { stOption.setSelected(false); } } } cfg.setValue(new Gson().toJson(stSelect)); } ConfigDAO.update(cfg); com.ikon.core.Config.reload(sc, new Properties()); // Activity log UserActivity.log(userId, "ADMIN_CONFIG_EDIT", cfg.getKey(), null, cfg.toString()); list(userId, filter, request, response); } else if (action.equals("delete")) { ConfigDAO.delete(cfg.getKey()); com.ikon.core.Config.reload(sc, new Properties()); // Activity log UserActivity.log(userId, "ADMIN_CONFIG_DELETE", cfg.getKey(), null, null); list(userId, filter, request, response); } else if (action.equals("import")) { dbSession = HibernateUtil.getSessionFactory().openSession(); importConfig(userId, request, response, data, dbSession); // Activity log UserActivity.log(request.getRemoteUser(), "ADMIN_CONFIG_IMPORT", null, null, null); list(userId, filter, request, response); } } } catch (DatabaseException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (FileUploadException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (SQLException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } finally { HibernateUtil.close(dbSession); } }
From source file:com.ibm.btt.sample.SampleFileHandler.java
/** * Just handle one file upload in this handler, developer can extend to support * multi-files upload //from w ww . j av a 2s . com */ @Override public int saveFile(HttpServletRequest request) { int code = SAVE_FAILED; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); //config the memory cache, if above the cache, the file data will be // saved on cache folder factory.setSizeThreshold(memCacheSize); // set up cache folder, when uploading, the tmp file // will be saved in cache folder with a internal managed name. factory.setRepository(new File(cachePath)); ServletFileUpload upload = new ServletFileUpload(factory); // max size of a file upload.setSizeMax(maxSize); try { if (isExpired()) { return REQ_TIMEOUT; } List<FileItem> fileItems = upload.parseRequest(request); // save file from request code = uploadFilesFromReq(request, fileItems); } catch (SizeLimitExceededException e) { code = FILE_SIZE_EXCEED; } catch (FileUploadException e) { if (LOG.doDebug()) { LOG.debug("SampleFileHandler:saveFile() -- upload file stream was been cancelled", e); } } } return code; }
From source file:com.wordpress.metaphorm.authProxy.httpClient.impl.OAuthProxyConnectionApacheHttpCommonsClientImpl.java
private void preparePostMethod(HttpServletRequest httpServletRequest) throws IOException { // Create a standard POST request PostMethod postMethodProxyRequest = new PostMethod(this.getProxyURL(httpServletRequest)); // Forward the request headers setProxyRequestHeaders(httpServletRequest, postMethodProxyRequest); // Check if this is a mulitpart (file upload) POST if (ServletFileUpload.isMultipartContent(httpServletRequest)) { this.handleMultipartPost(postMethodProxyRequest, httpServletRequest); } else {// www . j av a 2 s .c om this.handleStandardPost(postMethodProxyRequest, httpServletRequest); } this.httpMethod = postMethodProxyRequest; }
From source file:it.univaq.servlet.Modifica_pub.java
protected boolean action_upload(HttpServletRequest request) throws FileUploadException, Exception { HttpSession s = SecurityLayer.checkSession(request); //dichiaro mappe Map pubb = new HashMap(); Map rist = new HashMap(); Map key = new HashMap(); Map files = new HashMap(); Map modifica = new HashMap(); int id = Integer.parseInt(request.getParameter("id")); if (ServletFileUpload.isMultipartContent(request)) { //La dimensione massima di ogni singolo file su system int dimensioneMassimaDelFileScrivibieSulFileSystemInByte = 10 * 1024 * 1024; // 10 MB //Dimensione massima della request int dimensioneMassimaDellaRequestInByte = 20 * 1024 * 1024; // 20 MB // Creo un factory per l'accesso al filesystem DiskFileItemFactory factory = new DiskFileItemFactory(); //Setto la dimensione massima di ogni file, opzionale factory.setSizeThreshold(dimensioneMassimaDelFileScrivibieSulFileSystemInByte); // Istanzio la classe per l'upload ServletFileUpload upload = new ServletFileUpload(factory); // Setto la dimensione massima della request upload.setSizeMax(dimensioneMassimaDellaRequestInByte); // Parso la riquest della servlet, mi viene ritornata una lista di FileItem con // tutti i field sia di tipo file che gli altri List<FileItem> items = upload.parseRequest(request); /*//from w w w . j a va 2s . com * La classe usata non permette di riprendere i singoli campi per * nome quindi dovremmo scorrere la lista che ci viene ritornata con * il metodo parserequest */ //scorro per tutti i campi inviati for (int i = 0; i < items.size(); i++) { FileItem item = items.get(i); // Controllo se si tratta di un campo di input normale if (item.isFormField()) { // Prendo solo il nome e il valore String name = item.getFieldName(); String value = item.getString(); if (name.equals("titolo") || name.equals("autore") || name.equals("descrizione")) { pubb.put(name, value); } else if (name.equals("isbn") || name.equals("editore") || name.equals("lingua") || name.equals("numpagine") || name.equals("datapubbl")) { rist.put(name, value); } else if (name.equals("key1") || name.equals("key2") || name.equals("key3") || name.equals("key4")) { key.put(name, value); } else if (name.equals("descrizionemod")) { modifica.put(name, value); } } // Se si stratta invece di un file else { // Dopo aver ripreso tutti i dati disponibili name,type,size //String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); long sizeInBytes = item.getSize(); //li salvo nella mappa files.put("name", fileName); files.put("type", contentType); files.put("size", sizeInBytes); //li scrivo nel db //Database.connect(); Database.insertRecord("files", files); //Database.close(); // Posso scriverlo direttamente su filesystem if (true) { File uploadedFile = new File( getServletContext().getInitParameter("uploads.directory") + fileName); // Solo se veramente ho inviato qualcosa if (item.getSize() > 0) { item.write(uploadedFile); } } } } pubb.put("idutente", s.getAttribute("userid")); modifica.put("userid", s.getAttribute("userid")); modifica.put("idpubb", id); try { // if(Database.updateRecord("keyword", key, "id="+id)){ //aggiorno ora la pubblicazione con tutti i dati Database.updateRecord("keyword", key, "id=" + id); Database.updateRecord("pubblicazione", pubb, "id=" + id); Database.updateRecord("ristampa", rist, "idpub=" + id); Database.insertRecord("storia", modifica); // //vado alla pagina di corretto inserimento return true; } catch (SQLException ex) { Logger.getLogger(Modifica_pub.class.getName()).log(Level.SEVERE, null, ex); } } else return false; return false; }