public Photo saveImg(FileItem item) throws Exception { Photo photo = new Photo(); String filename = item.getName(); if (filename == null || filename.length() == 0) { log.error("img name illegal"); return null; } int index = filename.lastIndexOf("."); String type = filename.substring(index + 1); if (!ImgTools.checkImgFormatValidata(type)) { log.error("img type illegal"); return null; } ObjectId id = ObjectIdGenerator.generate(); // filename = new ObjectId() + filename.substring(index); photo.setId(id.toString()); photo.setType(type); GridFS mphoto = new GridFS(MongoDBPool.getInstance().getDB(), collection); GridFSInputFile in = null; in = mphoto.createFile(item.getInputStream()); in.setId(id); in.setFilename(id.toString()); in.setContentType(type); in.save(); item.getInputStream().close(); return photo; }
@Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { StringBuffer response = new StringBuffer(); for (FileItem item : sessionFiles) { if (false == item.isFormField()) { try { if (item.getName().endsWith(".xls")) { POIFSFileSystem fs = new POIFSFileSystem(item.getInputStream()); HSSFWorkbook wb = new HSSFWorkbook(fs); System.out.println("Sheet Num:" + wb.getNumberOfSheets()); // only get first sheet,ignore others HSSFSheet sheet = wb.getSheetAt(0); Iterator<Row> rows = sheet.rowIterator(); while (rows.hasNext()) { HSSFRow row = (HSSFRow) rows.next(); Iterator<Cell> cells = row.cellIterator(); while (cells.hasNext()) { HSSFCell cell = (HSSFCell) cells.next(); response.append(cell.toString() + ":"); } response.append("\n"); } } else if (item.getName().endsWith(".xlsx")) { // POIFSFileSystem fs = new POIFSFileSystem(item.getInputStream()); XSSFWorkbook wb = new XSSFWorkbook(item.getInputStream()); System.out.println("Sheet Num:" + wb.getNumberOfSheets()); // only get first sheet,ignore others XSSFSheet sheet = wb.getSheetAt(0); Iterator<Row> rows = sheet.rowIterator(); while (rows.hasNext()) { XSSFRow row = (XSSFRow) rows.next(); Iterator<Cell> cells = row.cellIterator(); while (cells.hasNext()) { XSSFCell cell = (XSSFCell) cells.next(); response.append(cell.toString() + ":"); } response.append("\n"); } } } catch (Exception e) { throw new UploadActionException(e); } } } // / Remove files from session because we have a copy of them removeSessionFileItems(request); // / Send your customized message to the client. return response.toString(); }
@Put public AttachmentResponse addAttachment(Representation entity) { if (authenticate() == false) return null; String taskId = (String) getRequest().getAttributes().get("taskId"); try { RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory()); List<FileItem> items = upload.parseRepresentation(entity); FileItem uploadItem = null; for (FileItem fileItem : items) { if (fileItem.getName() != null) { uploadItem = fileItem; } } String fileName = uploadItem.getName(); Attachment attachment = ActivitiUtil.getTaskService() .createAttachment( uploadItem.getContentType(), taskId, null, fileName, fileName, uploadItem.getInputStream()); return new AttachmentResponse(attachment); } catch (Exception e) { throw new ActivitiException("Unable to add new attachment to task " + taskId); } }
/** * Returns an {@link java.io.InputStream InputStream} that can be used to retrieve the contents of * the file. */ public InputStream getInputStream() throws IOException { InputStream result = null; if (fileItem != null) { result = fileItem.getInputStream(); } return result; }
public static final File writeFileItemToFolder( FileItem fileItem, File folder, boolean overwrite, boolean rename) throws IOException { if (!folder.isDirectory()) { return null; } File file = new File( URLHelper.mergePath( folder.getAbsolutePath(), StringHelper.createFileName(StringHelper.getFileNameFromPath(fileItem.getName())))); if (!file.exists()) { file.createNewFile(); } else { if (!overwrite && !rename) { throw new FileExistsException("File already exists."); } if (rename) { file = ResourceHelper.getFreeFileName(file); } } InputStream in = null; try { in = fileItem.getInputStream(); writeStreamToFile(in, file); return file; } catch (IOException e) { ResourceHelper.closeResource(in); file.delete(); throw e; } finally { ResourceHelper.closeResource(in); } }
private static String uploadPhoto(HttpServletRequest request) { logger.debug("load photo"); try { File fileSaveDir = new File(SAVE_DIR); if (!fileSaveDir.exists()) { fileSaveDir.mkdir(); } FileItem fileItem = (FileItem) request.getAttribute("photo"); if (fileItem == null) { return null; } String uuidFileName = UUID.randomUUID().toString() + "." + PHOTO_TYPE; File uploadedFile = new File(SAVE_DIR + File.separator + uuidFileName); uploadedFile.createNewFile(); OutputStream imageOutput = new FileOutputStream(uploadedFile); if (!resizeImage(fileItem.getInputStream(), imageOutput, PHOTO_WIDTH, PHOTO_HEIGHT)) { throw new Exception("Failed to resize the image"); } imageOutput.flush(); imageOutput.close(); // fileItem.write(uploadedFile); return uuidFileName; } catch (Exception e) { logger.error("Error on saving uploaded photo.", e); return null; } }
public void handle(FileItem item, Map<String, Object> result) { BlobWriter writer = blobManager.newFile(item.getContentType()); OutputStream out = writer.getOutputStream(); InputStream in = null; try { in = item.getInputStream(); try { int size = 0; while ((size = in.read(buffer)) != -1) { out.write(buffer, 0, size); } } finally { IOTools.close(in, out); } BlobInfo info = writer.getBlobInfo(); result.put("fileId", info.id()); result.put("contentType", info.contentType()); result.put("md5", info.md5()); result.put("sucessful", "true"); blobManager.commit(writer); } catch (Exception ex) { result.put("sucessful", "false"); blobManager.cancel(writer); } }
/** * 上传一般模块的图片 * * @param items * @param dir * @return */ public static String upload(List<FileItem> items, String dir) { String filePath = ""; String fileName; Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("HH-mm-ss"); if (items == null || items.isEmpty()) { return ""; } for (FileItem item : items) { if (!item.isFormField()) { try { String type = item.getName().substring((item.getName().lastIndexOf("."))); fileName = item.getName().substring(0, item.getName().indexOf(".")); fileName = fileName + "(" + format.format(date) + ")" + type; if (!Constants.PICTURE_TYPE.contains(type.toLowerCase())) { // 限制文件上传类型 return ""; } File tempFile = new File(dir); if (!tempFile.exists()) { // 如果文件夹不存在 tempFile.mkdirs(); // 创建一个新的空文件夹 } zoomOut(item.getInputStream(), fileName, dir); filePath = dir + "\\" + fileName; } catch (Exception ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } } } return filePath; }
@Override protected void service() throws ServletException, IOException { HttpServletRequest request = getRequest(); String path = null; DiskFileItemFactory factory = new DiskFileItemFactory(5 * 1024, new File(Configuration.getContextPath("temp"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(3 * 1024 * 1024); try { List<FileItem> items = upload.parseRequest(request); FileItem fileItem = null; if (items != null && items.size() > 0 && StringUtils.isNotBlank((fileItem = items.get(0)).getName())) { String fileName = fileItem.getName(); if (!fileName.endsWith(".jpg") && !fileName.endsWith(".gif") && !fileName.endsWith(".png")) { writeText("format_error"); return; } path = ImageUtil.generatePath(fileItem.getName()); IOUtil.copy(fileItem.getInputStream(), Configuration.getContextPath(path)); fileItem.delete(); writeText(Configuration.getSiteUrl(path)); } } catch (FileUploadException e) { throw new RuntimeException(e); } }
@Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { if (logger.isDebugEnabled()) { logger.debug( "The id = " + request.getParameter("pid") + " imageNum = " + request.getParameter("imageNum")); } ContentholderDAO cDAO = contentholderDAOProvider.get(); ContentitemsDAO itemDAO = itemDAOProvider.get(); String idStr = request.getParameter("pid"); String imageNum = request.getParameter("imageNum"); Integer id = Integer.parseInt(idStr); Contentholder holder = cDAO.get(id); GharondaThumbnails stn = new GharondaThumbnails(getServletContext().getRealPath("/")); BaseContentSvcHelper helper = null; try { helper = new BaseContentSvcHelper(imageNum, holder, stn, cDAO, itemDAO); } catch (Exception e) { e.printStackTrace(); } for (FileItem item : sessionFiles) { try { helper.store(item.getInputStream()); break; } catch (IOException e) { e.printStackTrace(); } } removeSessionFileItems(request, true); return ""; }
/** Returns an InputStream that can be used to retrieve the contents of the uploaded file. */ public InputStream getInputStream() { try { return fileItem.getInputStream(); // throws IOException } catch (Exception e) { throw new RuntimeException("Getting input stream of uploaded file failed (" + this + ")", e); } }
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // processRequest(request, response); String p = ""; ProfileParser pp = new ProfileParser(); try { List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { // String ajaxUpdateResult = "Field " + item.getFieldName() + // " with value: " + item.getString() + " is successfully read\n\r"; } else { // String fileName = item.getName(); InputStream content = item.getInputStream(); // response.setContentType("text/plain"); // response.setCharacterEncoding("UTF-8"); p = pp.parseProfile(content); // System.out.println(Streams.asString(content)); } } } catch (FileUploadException e) { throw new ServletException("Parsing file upload failed.", e); } // InputStream fileInput = request.getInputStream(); // String p = pp.parseProfile(fileInput); response.getWriter().write(p); }
/** * Get an uploaded file item. * * @param request * @param response * @throws IOException */ public void getUploadedFile(HttpServletRequest request, HttpServletResponse response) throws IOException { String parameter = request.getParameter(PARAM_SHOW); FileItem item = findFileItem(getSessionFileItems(request), parameter); if (item != null) { logger.debug( "UPLOAD-SERVLET (" + request.getSession().getId() + ") getUploadedFile: " + parameter + " returning: " + item.getContentType() + ", " + item.getName() + ", " + item.getSize() + " bytes"); response.setContentType(item.getContentType()); copyFromInputStreamToOutputStream(item.getInputStream(), response.getOutputStream()); } else { logger.info( "UPLOAD-SERVLET (" + request.getSession().getId() + ") getUploadedFile: " + parameter + " file isn't in session."); renderXmlResponse(request, response, ERROR_ITEM_NOT_FOUND); } }
public static BinaryData createBinaryData(final FileItem fileItem, final String label) throws VerticalAdminException { BinaryData binaryData = new BinaryData(); InputStream fis = null; try { binaryData.fileName = FileUtil.getFileName(fileItem); fis = fileItem.getInputStream(); ByteArrayOutputStream bao = new ByteArrayOutputStream(); byte[] buf = new byte[1024 * 10]; int size; while ((size = fis.read(buf)) > 0) { bao.write(buf, 0, size); } binaryData.data = bao.toByteArray(); binaryData.label = label; } catch (IOException e) { VerticalAdminLogger.errorAdmin(AdminHandlerBaseServlet.class, 20, "I/O error: %t", e); } finally { try { if (fis != null) { fis.close(); } } catch (IOException ioe) { String message = "Failed to close file input stream: %t"; VerticalAdminLogger.warn(AdminHandlerBaseServlet.class, 0, message, ioe); } } return binaryData; }
public InputStream getInputStream() { try { return wrapped.getInputStream(); } catch (IOException ex) { throw new RuntimeException(ex); } }
private FileTemp getFileInfo(HttpServletRequest request, HttpServletResponse response) throws IOException { try { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); String status = ""; InputStream is = null; String fileName = ""; for (Iterator<FileItem> i = items.iterator(); i.hasNext(); ) { FileItem item = i.next(); if (item.isFormField()) { if (item.getFieldName().equals("status_text")) { status = new String(item.get()); } } else { fileName = item.getName(); is = item.getInputStream(); } } return new FileTemp(fileName, is, status); } catch (FileUploadException e) { return null; } }
public void deployByZip(Map<String, Object> params) { ZipInputStream zipInputStream = null; try { FileItem file = (FileItem) params.get("processFile"); if (null != file) { zipInputStream = new ZipInputStream(file.getInputStream()); String deploymentId = StringUtil.getString(params.get("deploymentId")); DeploymentBuilder deploymentBuilder = modelService.createDeployment(); deploymentBuilder.addZipInputStream(zipInputStream); // 有deploymentID则为更新,否则为新增 if (StringUtil.isNotEmpty(deploymentId)) { deploymentBuilder.updateDeploymentId(deploymentId); } deploymentBuilder.deploy(); } } catch (IOException e) { throw new FoxbpmWebException(e); } finally { if (null != zipInputStream) { try { zipInputStream.close(); } catch (IOException e) { throw new FoxbpmWebException(e); } } } }
public void addNewKey(String alias, Iterator<FileItem> uploadedFilesIterator) throws Exception { PrivateKey privateKey = null; Certificate[] certs = null; while (uploadedFilesIterator.hasNext()) { FileItem fileItem = uploadedFilesIterator.next(); if (!fileItem.isFormField()) { if ("keyFile".equals(fileItem.getFieldName())) { KeyFactory kf = KeyFactory.getInstance("RSA"); privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(fileItem.get())); } if ("certFile".equals(fileItem.getFieldName())) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); certs = cf.generateCertificates(fileItem.getInputStream()).toArray(new Certificate[] {}); } } } if (privateKey == null || certs == null) { throw new WebApplicationException( Response.ok("<pre>Can't find input file.</pre>", MediaType.TEXT_HTML).build()); } keystore.setKeyEntry(alias, privateKey, keyStorePassword.toCharArray(), certs); save(); }
/** * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { // Extract the relevant content from the POST'd form if (ServletFileUpload.isMultipartContent(req)) { Map<String, String> responseMap; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request String deploymentType = null; String version = null; String fileName = null; InputStream artifactContent = null; try { List<FileItem> items = upload.parseRequest(req); for (FileItem item : items) { if (item.isFormField()) { if (item.getFieldName().equals("deploymentType")) { // $NON-NLS-1$ deploymentType = item.getString(); } else if (item.getFieldName().equals("version")) { // $NON-NLS-1$ version = item.getString(); } } else { fileName = item.getName(); if (fileName != null) fileName = FilenameUtils.getName(fileName); artifactContent = item.getInputStream(); } } // Default version is 1.0 if (version == null || version.trim().length() == 0) { version = "1.0"; // $NON-NLS-1$ } // Now that the content has been extracted, process it (upload the artifact to the s-ramp // repo). responseMap = uploadArtifact(deploymentType, fileName, version, artifactContent); } catch (SrampAtomException e) { responseMap = new HashMap<String, String>(); responseMap.put("exception", "true"); // $NON-NLS-1$ //$NON-NLS-2$ responseMap.put("exception-message", e.getMessage()); // $NON-NLS-1$ responseMap.put("exception-stack", ExceptionUtils.getRootStackTrace(e)); // $NON-NLS-1$ } catch (Throwable e) { responseMap = new HashMap<String, String>(); responseMap.put("exception", "true"); // $NON-NLS-1$ //$NON-NLS-2$ responseMap.put("exception-message", e.getMessage()); // $NON-NLS-1$ responseMap.put("exception-stack", ExceptionUtils.getRootStackTrace(e)); // $NON-NLS-1$ } finally { IOUtils.closeQuietly(artifactContent); } writeToResponse(responseMap, response); } else { response.sendError( HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, Messages.i18n.format("DeploymentUploadServlet.ContentTypeInvalid")); // $NON-NLS-1$ } }
private void processFile(FileItem item) { imageSize = item.getSize(); try { imageIs = item.getInputStream(); } catch (IOException e) { imageIs = null; imageSize = 0; } }
/** 上传ruleset */ public void upRuleset() throws Exception { /** * form中的enctype必须是multipart/... 组件提供方法检测form表单的enctype属性 在isMultipartContent方法中同时检测了是否是post提交 * 如果不是post提交则返回false */ if (ServletFileUpload.isMultipartContent(request)) { String RulePath = (String) application.getAttribute("Ruleset"); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(new File(RulePath + "tmp")); // 临时文件目录 // 内存最大占用 factory.setSizeThreshold(1024000); ServletFileUpload sfu = new ServletFileUpload(factory); // 单个文件最大值byte sfu.setFileSizeMax(102400000); // 所有上传文件的总和最大值byte sfu.setSizeMax(204800000); List<FileItem> items = null; try { items = sfu.parseRequest(request); } catch (SizeLimitExceededException e) { error("size limit exception!"); return; } catch (Exception e) { error("Exception:" + e.getMessage()); return; } Json j = new Json(1, "ok"); JsonObjectNode data = j.createData(); JsonArrayNode files = new JsonArrayNode("filename"); data.addChild(files); Iterator<FileItem> iter = (items == null) ? null : items.iterator(); while (iter != null && iter.hasNext()) { FileItem item = (FileItem) iter.next(); // 文件域 if (!item.isFormField()) { String fileName = item.getName(); int index = fileName.lastIndexOf("\\"); if (index < 0) index = 0; fileName = fileName.substring(index); if (!fileName.endsWith(".xml")) fileName += ".xml"; BufferedInputStream in = new BufferedInputStream(item.getInputStream()); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(RulePath + fileName))); Streams.copy(in, out, true); files.addItem(new JsonLeafNode("", fileName)); } } echo(j.toString()); } else { error("enctype error!"); } }
@SuppressWarnings("unchecked") @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletFileUpload servletFileUpload = setUpServletFileUpload(); ContestManager contestManager = SessionUtil.getInstance().getContestManager(); List<FileItem> fileItemsList = null; try { fileItemsList = servletFileUpload.parseRequest(request); } catch (FileUploadException e) { setError( request, response, "File upload did not finish successfully. Or you might be using an unsupported browser."); return; } InputStream inputStream = null; Map<String, String> fieldValues = new HashMap<String, String>(); for (FileItem fileItem : fileItemsList) { if (fileItem.isFormField()) { fieldValues.put(fileItem.getFieldName(), fileItem.getString()); } else { inputStream = fileItem.getInputStream(); break; } } if (inputStream == null) { setError(request, response, "No file seems to be uploaded."); return; } Task task = getTastInfo(fieldValues, contestManager); if (task == null) { setError(request, response, "Error reading task infomation."); return; } try { List<String> messages = unzipStream( request, response, inputStream, task, contestManager, fieldValues.get("contestId")); request.getSession().setAttribute("messages", messages); } finally { try { inputStream.close(); } catch (IOException e) { } } response.sendRedirect( "editTask?contestId=" + fieldValues.get("contestId") + "&taskId=" + task.getId()); }
/** * The doPost method of the servlet. <br> * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); // InputStream is = request.getInputStream(); // InputStreamReader isr = new InputStreamReader(is); // char[] c = new char[100]; // while(isr.read(c)!=-1){ // System.out.println(c); // } String path = request.getRealPath("/"); String savePath = path + "file\\"; String tempPath = path + "temp\\"; File f = new File(tempPath); // byte[] b = new byte[1]; // int len = 0; // while((len=is.read(b))!=-1){ // fos.write(b,0,len); // } // fos.flush(); // fos.close(); // is.close(); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(f); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(1024 * 1024 * 1024); List<FileItem> items = new ArrayList<FileItem>(); try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } for (FileItem fileItem : items) { System.out.println(fileItem.getName()); System.out.println(fileItem.getFieldName()); System.out.println(fileItem.getSize()); InputStream is = fileItem.getInputStream(); FileOutputStream fos = new FileOutputStream(savePath + fileItem.getName()); byte[] b = new byte[1024]; int len = 0; while ((len = is.read(b)) != -1) { fos.write(b, 0, len); } fos.flush(); fos.close(); is.close(); } }
protected void processFile(FileItem item, String name, MutableRequest request) { try { String fileName = FilenameUtils.getName(item.getName()); UploadedFile upload = new DefaultUploadedFile( item.getInputStream(), fileName, item.getContentType(), item.getSize()); request.setParameter(name, name); request.setAttribute(name, upload); logger.debug("Uploaded file: {} with {}", name, upload); } catch (IOException e) { throw new InvalidParameterException("Can't parse uploaded file " + item.getName(), e); } }
public void initialize(GWikiContext wikiContext, FileItem dataFile, String pathPrefix) { if (dataFile == null) { wikiContext.addSimpleValidationError("No Zip available"); return; } try { mountZipFileSystem(dataFile.getInputStream(), wikiContext, pathPrefix); } catch (Exception ex) { wikiContext.addSimpleValidationError( "Failure while mounting Zip File System: " + ex.getMessage()); return; } }
/** * 获取Excel数据,返回List<String[]> * * @param sheetNumber 读取工作表的下标(从1开始).可有可无,默认读取所有表单. */ public static final List<String[]> excelToArrayList(FileItem fileItem, int... sheetNumber) throws Exception { List<String[]> resultList = null; InputStream is = null; try { is = fileItem.getInputStream(); resultList = excelToArrayList(is, sheetNumber); } catch (Exception e) { throw e; } finally { if (is != null) { is.close(); } } return resultList; }
/** * 读取Excel中的数据.将这些数据放入到一个三维数组中. * * @param sheetNumber 读取工作表的下标(从1开始).可有可无,默认读取所有表单. */ public static final ArrayList<ArrayList<Object>> readExcel(FileItem fileItem, int... sheetNumber) throws Exception { ArrayList<ArrayList<Object>> subdata = null; InputStream is = null; try { is = fileItem.getInputStream(); subdata = readExcel(is, sheetNumber); } catch (Exception e) { throw e; } finally { if (is != null) { is.close(); } } return subdata; }
private String getFile(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 如果是文件上传类型 StringBuffer fileStr = new StringBuffer(); // PrintWriter out = resp.getWriter(); if (ServletFileUpload.isMultipartContent(req)) { // 得到文件上传工厂 DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(5000 * 1024); factory.setRepository(new File("c:/temp")); // 处理文件上传核心类 ServletFileUpload fileUpload = new ServletFileUpload(factory); fileUpload.setFileSizeMax(50000 * 1024); // 设置文件上传类的编码格式 fileUpload.setHeaderEncoding("UTF-8"); // 集合数据 : FileItem对象 注意: 每一个表单域 对应一个 FileItem对象(封装) try { List<FileItem> fileItemList = fileUpload.parseRequest(req); for (FileItem item : fileItemList) { // 如果这个文本域是文件类型的 if (!item.isFormField()) { CustomLog.info(item.getFieldName()); InputStream inputStream = item.getInputStream(); BufferedInputStream bis = new BufferedInputStream(inputStream); int tempbyte; while ((tempbyte = bis.read()) != -1) { char c = (char) tempbyte; System.out.write(tempbyte); fileStr.append(c); } } else { // CustomLog.info(item.getFieldName()); // CustomLog.info(item.getString()); } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return fileStr.toString(); }
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void insertarFormularioImpuesto( FileItem bf, String separadorCampos, Integer numeroFormulario) throws Exception { try { InputStream uploadedStream = bf.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(uploadedStream)); String[] lineas = LectorConfiguracionSet.lineasDelArchivo(new BufferedReader(reader)); uploadedStream.close(); for (String linea : lineas) { String[] token = LectorConfiguracionSet.tokensDeLaLinea(linea, separadorCampos); if (FORM_IMP_POS_FORMULARIO < token.length) { if ((numeroFormulario == null) || (Integer.parseInt(token[FORM_IMP_POS_FORMULARIO]) == numeroFormulario)) { Integer impuesto; if (FORM_IMP_POS_IMPUESTO < token.length && token[FORM_IMP_POS_IMPUESTO].length() >= 0) { impuesto = Integer.parseInt(token[FORM_IMP_POS_IMPUESTO]); } else { throw new Exception("No contiene numero de impuesto"); } String obligacion = null; if (FORM_IMP_POS_OBLIGACION < token.length && token[FORM_IMP_POS_OBLIGACION].length() >= 0) { obligacion = token[FORM_IMP_POS_OBLIGACION]; } FormularioImpuesto fi = new FormularioImpuesto(); fi.setImpuesto(impuesto); fi.setNumeroFormulario(Integer.parseInt(token[FORM_IMP_POS_FORMULARIO])); if (this.total(fi) == 0) { fi.setObligacion(obligacion); this.save(fi); } else { fi = this.get(fi); fi.setObligacion(obligacion); this.update(fi); } } } } } catch (Exception e) { // abortar transaccion context.setRollbackOnly(); e.printStackTrace(); throw e; } }
/** * 上传活动剪影模块的图片 * * @param items * @param dir * @return */ public static String uploadHdjy(List<FileItem> items, String dir, int hdid) { String filePath = ""; String fileName; Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("HH-mm-ss"); if (items == null || items.isEmpty()) { return ""; } for (FileItem item : items) { if (!item.isFormField()) { try { String type = item.getName().substring((item.getName().lastIndexOf("."))); fileName = item.getName().substring(0, item.getName().indexOf(".")); fileName = fileName + "(" + format.format(date) + ")" + type; if (!Constants.PICTURE_TYPE.contains(type.toLowerCase())) { // 限制文件上传类型 return ""; } File tempFile = new File(dir); if (!tempFile.exists()) { // 如果文件夹不存在 tempFile.mkdirs(); // 创建一个新的空文件夹 } zoomOut(item.getInputStream(), fileName, dir); filePath = dir + "\\" + fileName; // 把上传的活动剪影的信息同步写入数据库 String filename = dir + "\\" + fileName; String temp = filename.substring(filename.indexOf("image") - 1); String databaseName = temp.replaceAll("\\\\", "/"); Sthd sthd = new Sthd(); sthd.setHdid(hdid); Hyberbin hyb = new Hyberbin(sthd, true); sthd = hyb.showOne("select hdid,hdsj from sthd"); Hdjy hdjy = new Hdjy(); hyb.changeTable(hdjy); hdjy.setHdid(hdid); hdjy.setJytp(databaseName); hdjy.setJysj(sthd.getHdsj()); hyb.insert("jyid"); hyb.reallyClose(); } catch (Exception ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } } } return filePath; }