List of usage examples for org.apache.commons.fileupload FileItem getInputStream
InputStream getInputStream() throws IOException;
From source file:com.nominanuda.web.http.ServletHelper.java
@SuppressWarnings("unchecked") private HttpEntity buildEntity(HttpServletRequest servletRequest, final InputStream is, long contentLength, String ct, String cenc) throws IOException { if (ServletFileUpload.isMultipartContent(servletRequest)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items; try {//from w w w . j ava 2 s . co m items = upload.parseRequest(new HttpServletRequestWrapper(servletRequest) { public ServletInputStream getInputStream() throws IOException { return new ServletInputStream() { public int read() throws IOException { return is.read(); } public int read(byte[] arg0) throws IOException { return is.read(arg0); } public int read(byte[] b, int off, int len) throws IOException { return is.read(b, off, len); } //@Override @SuppressWarnings("unused") public boolean isFinished() { Check.illegalstate.fail(NOT_IMPLEMENTED); return false; } //@Override @SuppressWarnings("unused") public boolean isReady() { Check.illegalstate.fail(NOT_IMPLEMENTED); return false; } //@Override @SuppressWarnings("unused") public void setReadListener(ReadListener arg0) { Check.illegalstate.fail(NOT_IMPLEMENTED); } }; } }); } catch (FileUploadException e) { throw new IOException(e); } MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (FileItem i : items) { multipartEntity.addPart(i.getFieldName(), new InputStreamBody(i.getInputStream(), i.getName())); } return multipartEntity; } else { InputStreamEntity entity = new InputStreamEntity(is, contentLength); entity.setContentType(ct); if (cenc != null) { entity.setContentEncoding(cenc); } return entity; } }
From source file:UploadImage.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // change the following parameters to connect to the oracle database String username = "wang8"; String password = "Steelrose101"; String drivername = "oracle.jdbc.driver.OracleDriver"; String dbstring = "jdbc:oracle:thin:@gwynne.cs.ualberta.ca:1521:CRS"; int pic_id;// w ww . j a va 2s.c o m try { //Parse the HTTP request to get the image stream DiskFileUpload fu = new DiskFileUpload(); List FileItems = fu.parseRequest(request); // Process the uploaded items, assuming only 1 image file uploaded Iterator i = FileItems.iterator(); FileItem item = (FileItem) i.next(); while (i.hasNext() && item.isFormField()) { item = (FileItem) i.next(); } //Get the image stream InputStream instream = item.getInputStream(); // Connect to the database and create a statement Connection conn = getConnected(drivername, dbstring, username, password); Statement stmt = conn.createStatement(); /* * First, to generate a unique pic_id using an SQL sequence */ ResultSet rset1 = stmt.executeQuery("SELECT pic_id_sequence.nextval from dual"); rset1.next(); pic_id = rset1.getInt(1); //Insert an empty blob into the table first. Note that you have to //use the Oracle specific function empty_blob() to create an empty blob stmt.execute("INSERT INTO pictures VALUES(" + pic_id + ",'test',empty_blob())"); // to retrieve the lob_locator // Note that you must use "FOR UPDATE" in the select statement String cmd = "SELECT * FROM pictures WHERE pic_id = " + pic_id + " FOR UPDATE"; ResultSet rset = stmt.executeQuery(cmd); rset.next(); BLOB myblob = ((OracleResultSet) rset).getBLOB(3); //Write the image to the blob object OutputStream outstream = myblob.getBinaryOutputStream(); int size = myblob.getBufferSize(); byte[] buffer = new byte[size]; int length = -1; while ((length = instream.read(buffer)) != -1) outstream.write(buffer, 0, length); instream.close(); outstream.close(); stmt.executeUpdate("commit"); response_message = " Upload OK! "; conn.close(); } catch (Exception ex) { //System.out.println( ex.getMessage()); response_message = ex.getMessage(); } //Output response to the client response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n" + "<HTML>\n" + "<HEAD><TITLE>Upload Message</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>" + response_message + "</H1>\n" + "</BODY></HTML>"); }
From source file:com.sishistorico.sv.SvEditarEleitor.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w ww . j a va2 s . c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF8"); response.setContentType("text/html;charset=UTF-8"); List<FileItem> items = null; byte[] foto = null; long vazio = 0; try { items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { vazio = item.getSize(); System.out.println("tamanho/:::::::::::::::::::: " + vazio); InputStream imageInput = item.getInputStream(); Image image = ImageIO.read(imageInput); BufferedImage thumb = Imagem.redimensionar(image, 400, 500); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(thumb, "JPG", baos); baos.flush(); foto = baos.toByteArray(); baos.close(); } } //dados do formulrio e metodos para salvar DateFormat formatter; Date date; formatter = new SimpleDateFormat("dd/MM/yyyy"); date = (Date) formatter.parse(items.get(1).getString()); // fim do tratamento Eleitor el = new Eleitor(); Endereco end = new Endereco(); el.setId(Integer.parseInt(items.get(19).getString("UTF-8").trim())); el.setNome(items.get(0).getString("UTF-8").trim()); el.setData_nascimento(date); el.setCpf(items.get(2).getString("UTF-8").replaceAll("\\.|\\-|\\ ", "").trim()); el.setRg(items.get(3).getString("UTF-8").replaceAll("\\.|\\-|\\ ", "").trim()); el.setSus(items.get(4).getString("UTF-8").replaceAll("\\.|\\-|\\ ", "").trim()); el.setEmail(items.get(5).getString("UTF-8")); el.setTelefone(items.get(6).getString("UTF-8").replaceAll("\\(|\\)|\\-|\\ ", "").trim()); el.setWhats(items.get(7).getString("UTF-8").replaceAll("\\(|\\)|\\-|\\ ", "").trim()); el.setObs(items.get(8).getString("UTF-8").trim()); el.setReferencia_pessoal(items.get(9).getString("UTF-8").trim()); end.setRua(items.get(11).getString("UTF-8").trim()); end.setBairro(items.get(12).getString("UTF-8").trim()); end.setN(items.get(13).getString("UTF-8").trim()); end.setCidade(items.get(14).getString("UTF-8").trim()); end.setCep(items.get(15).getString("UTF-8").trim()); end.setLocalidade(Integer.parseInt(items.get(16).getString("UTF-8").trim())); el.setTipo(Integer.parseInt(items.get(17).getString("UTF-8").trim())); el.setPertence(Integer.parseInt(items.get(18).getString("UTF-8").trim())); el.setEnd(end); DaoEleitor daoEleitor = new DaoEleitor(); DaoFoto daoFoto = new DaoFoto(); int idretorno = daoEleitor.Eleitor_Editar(el); if (vazio > 1) { daoFoto.atualizarImagem(foto, idretorno); } response.sendRedirect("editar_eleitor.jsp?id=" + el.getId() + "&msgok=Editado com sucesso!"); } catch (FileUploadException ex) { Logger.getLogger(SvEditarEleitor.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(SvEditarEleitor.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(SvEditarEleitor.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(SvEditarEleitor.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:es.ucm.fdi.dalgs.user.service.UserService.java
@PreAuthorize("hasRole('ROLE_ADMIN')") @Transactional(readOnly = false)//from w ww .j ava 2 s. c om public ResultClass<Boolean> uploadCVS(UploadForm upload, String typeOfUser, Locale locale) { ResultClass<Boolean> result = new ResultClass<>(); if (!upload.getFileData().isEmpty()) { CsvPreference prefers = new CsvPreference.Builder(upload.getQuoteChar().charAt(0), upload.getDelimiterChar().charAt(0), upload.getEndOfLineSymbols()).build(); List<User> list = null; try { FileItem fileItem = upload.getFileData().getFileItem(); UserCSV userUpload = new UserCSV(); list = userUpload.readCSVUserToBean(fileItem.getInputStream(), upload.getCharset(), prefers, typeOfUser); if (list == null) { result.setHasErrors(true); result.getErrorsList().add(messageSource.getMessage("error.params", null, locale)); } else { if (repositoryUser.persistListUsers(list)) { for (User u : list) { User aux = findByUsername(u.getUsername()).getSingleElement(); manageAclService.addACLToObject(u.getId(), u.getClass().getName()); manageAclService.addPermissionToAnObject_WRITE(aux, aux.getId(), aux.getClass().getName()); } result.setSingleElement(true); } } } catch (IOException e) { e.printStackTrace(); result.setSingleElement(false); } } else { result.setHasErrors(true); result.getErrorsList().add(messageSource.getMessage("error.fileEmpty", null, locale)); } return result; }
From source file:com.tc.webshell.servlets.Upload.java
/** * Processes requests for both HTTP/*from w w w . j a v a2s . c o m*/ * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @SuppressWarnings("unchecked") protected void processRequest(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("application/json"); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory); upload.setFileSizeMax(60000000); // Parse the request try { Database db = ContextInfo.getUserDatabase(); for (FileItem item : (List<FileItem>) upload.parseRequest(req)) { if (!item.isFormField()) { InputStream in = item.getInputStream(); File file = this.createTempFile("upload", item.getName()); OutputStream fout = new FileOutputStream(file); try { byte[] bytes = IOUtils.toByteArray(in); IOUtils.write(bytes, fout); Map<String, String> queryMap = XSPUtils.getQueryMap(req.getQueryString()); Document doc = null; if (queryMap.containsKey("documentId")) { doc = new DocFactory().attachToDocument(db, queryMap.get("documentId"), file); } else { doc = new DocFactory().buildDocument(req, db, file); } doc.save(); Prompt prompt = new Prompt(); prompt.setMessage("file uploaded successfully"); prompt.setTitle("info"); prompt.addProperty("noteId", doc.getNoteID()); prompt.addProperty("unid", doc.getUniversalID()); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd G 'at' HH:mm:ss z"); String strdate = formatter.format(doc.getCreated().toJavaDate()); prompt.addProperty("created", strdate); Vector<Item> items = doc.getItems(); for (Item notesItem : items) { prompt.addProperty(notesItem.getName(), notesItem.getText()); } String json = MapperFactory.mapper().writeValueAsString(prompt); this.compressResponse(req, res, json); doc.recycle(); } finally { in.close(); if (fout != null) { fout.close(); file.delete();//make sure we cleanup } } } else { // } break; } } catch (Exception e) { logger.log(Level.SEVERE, null, e); } finally { res.getOutputStream().close(); } }
From source file:com.carolinarollergirls.scoreboard.jetty.MediaServlet.java
protected File createFile(File typeDir, FileItem item) throws IOException, FileNotFoundException { File f = new File(typeDir, item.getName()); FileOutputStream fos = null;//from ww w.j a v a 2s. c o m InputStream is = item.getInputStream(); try { fos = new FileOutputStream(f); IOUtils.copyLarge(is, fos); return f; } finally { is.close(); if (null != fos) fos.close(); } }
From source file:net.commerce.zocalo.JspSupport.ExperimenterScreen.java
public void processRequest(HttpServletRequest request, HttpServletResponse response) { Session session = SessionSingleton.getSession(); try {// w w w .ja v a 2 s.c o m if (null == action) { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = upload.parseRequest(request); for (Iterator iterator = items.iterator(); iterator.hasNext();) { FileItem fileItem = (FileItem) iterator.next(); if (fileItem.getFieldName().equals(FILENAME_FIELD)) { SessionSingleton.setSession(processStream(fileItem.getInputStream())); } } } } else if (session == null) { return; } else if (session.startRoundActionLabel().equalsIgnoreCase(action)) { session.startNextTimedRound(); } else if (DISPLAY_SCORES_ACTION.equals(action)) { if (session instanceof JudgingSession) { JudgingSession jSession = (JudgingSession) session; jSession.endScoringPhase(); message = ""; } else { message = "judging not enabled."; } } else if (STOP_VOTING_ACTION.equals(action)) { if (session instanceof VotingSession) { VotingSession vSession = (VotingSession) session; vSession.endVoting(); message = ""; } else { message = "judging not enabled."; } } else if (action != null && action.startsWith(session.stopRoundActionLabel())) { session.endTrading(true); } } catch (ScoreException e) { message = "unable to calculate scores. Have the judges entered estimates?"; } catch (IOException e) { return; } catch (Exception e) { return; } if (request != null && "POST".equals(request.getMethod())) { redirectResult(request, response); } }
From source file:MainServer.ImageUploadServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); try {/* www . j a va 2 s . c om*/ List<FileItem> items = this.upload.parseRequest(request); if (items != null && !items.isEmpty()) { for (FileItem item : items) { String filename = item.getName(); String filepath = fileDir + File.separator + filename; System.out.println("File path: " + filepath); File file = new File(filepath); InputStream inputStream = item.getInputStream(); BufferedInputStream bis = new BufferedInputStream(inputStream); FileOutputStream fos = new FileOutputStream(file); int f; while ((f = bis.read()) != -1) { fos.write(f); } fos.flush(); fos.close(); bis.close(); inputStream.close(); System.out.println("File: " + filename + "Uploaded"); } } System.out.println("Uploaded!"); out.write("Uploaded!"); } catch (FileUploadException | IOException e) { System.out.println(e); out.write(fileDir); } }
From source file:com.cognitivabrasil.repositorio.web.FileController.java
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST) @ResponseBody/*w ww .j ava 2s. c o m*/ public String upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, org.apache.commons.fileupload.FileUploadException { if (file == null) { file = new Files(); file.setSizeInBytes(0L); } Integer docId = null; String docPath = null; String responseString = RESP_SUCCESS; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { try { ServletFileUpload x = new ServletFileUpload(new DiskFileItemFactory()); List<FileItem> items = x.parseRequest(request); for (FileItem item : items) { InputStream input = item.getInputStream(); // Handle a form field. if (item.isFormField()) { String attribute = item.getFieldName(); String value = Streams.asString(input); switch (attribute) { case "chunks": this.chunks = Integer.parseInt(value); break; case "chunk": this.chunk = Integer.parseInt(value); break; case "filename": file.setName(value); break; case "docId": if (value.isEmpty()) { throw new org.apache.commons.fileupload.FileUploadException( "No foi informado o id do documento."); } docId = Integer.parseInt(value); docPath = Config.FILE_PATH + "/" + docId; File documentPath = new File(docPath); // cria o diretorio documentPath.mkdirs(); break; default: break; } } // Handle a multi-part MIME encoded file. else { try { File uploadFile = new File(docPath, item.getName()); BufferedOutputStream bufferedOutput; bufferedOutput = new BufferedOutputStream(new FileOutputStream(uploadFile, true)); byte[] data = item.get(); bufferedOutput.write(data); bufferedOutput.close(); } catch (Exception e) { LOG.error("Erro ao salvar o arquivo.", e); file = null; throw e; } finally { if (input != null) { try { input.close(); } catch (IOException e) { LOG.error("Erro ao fechar o ImputStream", e); } } file.setName(item.getName()); file.setContentType(item.getContentType()); file.setPartialSize(item.getSize()); } } } if ((this.chunk == this.chunks - 1) || this.chunks == 0) { file.setLocation(docPath + "/" + file.getName()); if (docId != null) { file.setDocument(documentsService.get(docId)); } fileService.save(file); file = null; } } catch (org.apache.commons.fileupload.FileUploadException | IOException | NumberFormatException e) { responseString = RESP_ERROR; LOG.error("Erro ao salvar o arquivo", e); file = null; throw e; } } // Not a multi-part MIME request. else { responseString = RESP_ERROR; } response.setContentType("application/json"); byte[] responseBytes = responseString.getBytes(); response.setContentLength(responseBytes.length); ServletOutputStream output = response.getOutputStream(); output.write(responseBytes); output.flush(); return responseString; }
From source file:UploadImage.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // change the following parameters to connect to the oracle database String username = "lingbo"; String password = "TlboSci1994"; String drivername = "oracle.jdbc.driver.OracleDriver"; String dbstring = "jdbc:oracle:thin:@gwynne.cs.ualberta.ca:1521:CRS"; int pic_id;/*from w w w .j a v a2 s.c o m*/ try { //Parse the HTTP request to get the image stream DiskFileUpload fu = new DiskFileUpload(); List FileItems = fu.parseRequest(request); // Process the uploaded items, assuming only 1 image file uploaded Iterator i = FileItems.iterator(); FileItem item = (FileItem) i.next(); while (i.hasNext() && item.isFormField()) { item = (FileItem) i.next(); } //Get the image stream InputStream instream = item.getInputStream(); BufferedImage img = ImageIO.read(instream); BufferedImage thumbNail = shrink(img, 10); // Connect to the database and create a statement Connection conn = getConnected(drivername, dbstring, username, password); Statement stmt = conn.createStatement(); /* * First, to generate a unique pic_id using an SQL sequence */ ResultSet rset1 = stmt.executeQuery("SELECT pic_id_sequence.nextval from dual"); rset1.next(); pic_id = rset1.getInt(1); //Insert an empty blob into the table first. Note that you have to //use the Oracle specific function empty_blob() to create an empty blob stmt.execute("INSERT INTO pictures VALUES(" + pic_id + ",'test',empty_blob())"); // to retrieve the lob_locator // Note that you must use "FOR UPDATE" in the select statement String cmd = "SELECT * FROM pictures WHERE pic_id = " + pic_id + " FOR UPDATE"; ResultSet rset = stmt.executeQuery(cmd); rset.next(); BLOB myblob = ((OracleResultSet) rset).getBLOB(3); //Write the image to the blob object OutputStream outstream = myblob.setBinaryStream(1); ImageIO.write(thumbNail, "jpg", outstream); /* int size = myblob.getBufferSize(); byte[] buffer = new byte[size]; int length = -1; while ((length = instream.read(buffer)) != -1) outstream.write(buffer, 0, length); */ instream.close(); outstream.close(); stmt.executeUpdate("commit"); response_message = " Upload OK! "; conn.close(); } catch (Exception ex) { //System.out.println( ex.getMessage()); response_message = ex.getMessage(); } //Output response to the client response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n" + "<HTML>\n" + "<HEAD><TITLE>Upload Message</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>" + response_message + "</H1>\n" + "</BODY></HTML>"); }