/** * 文件上传处理类 * * @return {@link UploadResult} * @throws Exception 抛出异常 */ public UploadResult upload() throws Exception { boolean multipartContent = ServletFileUpload.isMultipartContent(request); if (!multipartContent) { throw new RuntimeException("上传表单enctype类型设置错误"); } List<TextFormResult> textFormResultList = Lists.newArrayList(); List<FileFormResult> fileFormResultList = Lists.newArrayList(); List<FileItem> fileItems = upload.parseRequest(request); for (FileItem item : fileItems) { if (item.isFormField()) textFormResultList.add(processFormField(item)); else fileFormResultList.add(processUploadedFile(item)); } return new UploadResult(textFormResultList, fileFormResultList); }
/** * 获取Excel数据,返回List * * @param sheetNumber * 读取工作表的下标(从1开始).可有可无,默认读取所有表单. */ public static final List<String[]> excelToArrayList(String fileName, FileItem fileItem, int... sheetNumber) throws Exception { List<String[]> resultList = null; InputStream is = null; try { is = fileItem.getInputStream(); resultList = excelToArrayList(fileName, is, sheetNumber); } catch (Exception e) { throw e; } finally { if (is != null) { is.close(); } } return resultList; }
@Override public void process(Exchange exchange) throws Exception { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ExchangeFileUpload upload = new ExchangeFileUpload(factory); java.util.List<FileItem> items = upload.parseExchange(exchange); if(items.size() >= 1){ exchange.getIn().setBody(items.get(0).getInputStream()); for (int i = 1; i < items.size(); i++) { exchange.setProperty(items.get(i).getName(), items.get(i).getInputStream()); } } }
/** * 获取Excel数据,返回List<String[]> * * @param sheetNumber * 读取工作表的下标(从1开始).可有可无,默认读取所有表单. */ public static final List<String[]> excelToArrayList(String fileName, FileItem fileItem, int... sheetNumber) throws Exception { List<String[]> resultList = null; InputStream is = null; try { is = fileItem.getInputStream(); resultList = excelToArrayList(fileName, is, sheetNumber); } catch (Exception e) { throw e; } finally { if (is != null) { is.close(); } } return resultList; }
public void importProject(HttpServletRequest req, HttpServletResponse resp) throws Exception { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletContext servletContext = req.getSession().getServletContext(); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); factory.setRepository(repository); ServletFileUpload upload = new ServletFileUpload(factory); InputStream inputStream=null; boolean overwriteProject=true; List<FileItem> items = upload.parseRequest(req); if(items.size()==0){ throw new ServletException("Upload file is invalid."); } for(FileItem item:items){ String name=item.getFieldName(); if(name.equals("overwriteProject")){ String overwriteProjectStr=new String(item.get()); overwriteProject=Boolean.valueOf(overwriteProjectStr); }else if(name.equals("file")){ inputStream=item.getInputStream(); } } repositoryService.importXml(inputStream,overwriteProject); IOUtils.closeQuietly(inputStream); resp.sendRedirect(req.getContextPath()+"/urule/frame"); }
public void importExcelTemplate(HttpServletRequest req, HttpServletResponse resp) throws Exception { DiskFileItemFactory factory=new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(req); Iterator<FileItem> itr = items.iterator(); List<Map<String,Object>> mapData=null; while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); String name=item.getFieldName(); if(!name.equals("file")){ continue; } InputStream stream=item.getInputStream(); mapData=parseExcel(stream); httpSessionKnowledgeCache.put(req, IMPORT_EXCEL_DATA, mapData); stream.close(); break; } httpSessionKnowledgeCache.put(req, IMPORT_EXCEL_DATA, mapData); writeObjectToJson(resp, mapData); }
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception { // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) throw new IllegalArgumentException("Not multipart content!"); FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List<FileItem> items = GenericUtils.cast(upload.parseRequest(request)); // Process the uploaded items handleFormFields(request); for (FileItem item : items) { doUpload(request, document, item); } }
@Override public void handle( List<FileItem> fileItems ) { for ( FileItem file : fileItems ) { byte[] fileName = file.getName().getBytes(); try { String uploadName = new String( fileName, "utf-8" ); System.out.println( uploadName ); File writeFile = new File( "D:\\" + uploadName ); file.write( writeFile ); } catch ( Exception e ) { // TODO Auto-generated catch block e.printStackTrace(); } } }
@Override public void upload(HttpServletRequest request, HttpServletResponse response) { try { serviceHelper.setCors(request, response); OutputStream outputStream = serviceHelper.setContext(request, response, URI); List<UploadReader> readers = new ArrayList<>(); for (FileItem item : getUpload(request).parseRequest(request)) if (!item.isFormField()) readers.add(new HttpUploadReader(item)); outputStream.write(json.toBytes(uploadService.uploads(readers))); outputStream.flush(); outputStream.close(); } catch (Throwable e) { logger.warn(e, "处理文件上传时发生异常!"); } finally { closables.close(); } }
/** * {@inheritDoc} * <pre> * 一時ファイルの保存処理ですが、性能を考慮し本来のフォルダに保存します。 * </pre> */ @Override public File makeTempFromFileItem(final FileItem fileItem) throws Exception { this.fileName = FileUtil.getFileName(fileItem.getName()); File file = this.makeUniqFile(); FileOutputStream os = new FileOutputStream(file); try { InputStream is = fileItem.getInputStream(); try { FileUtil.copyStream(is, os); } finally { is.close(); } } finally { os.close(); } return file; }
/** * 文件上传 * * @param request * @return infos info[0] 验证文件域返回错误信息 info[1] 上传文件错误信息 info[2] savePath * info[3] saveUrl info[4] fileUrl */ @SuppressWarnings("unchecked") public String[] uploadFile(HttpServletRequest request) { String[] infos = new String[5]; // 验证 infos[0] = this.validateFields(request); // 初始化表单元素 Map<String, Object> fieldsMap = new HashMap<String, Object>(); if (infos[0].equals("true")) { fieldsMap = this.initFields(request); } // 上传 List<FileItem> fiList = (List<FileItem>) fieldsMap.get(UploadUtils.FILE_FIELDS); if (fiList != null) { for (FileItem item : fiList) { infos[1] = this.saveFile(item); } infos[2] = savePath; infos[3] = saveUrl; infos[4] = fileUrl; } return infos; }
public Map<String, Object> map(HttpServletRequest request) { ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); upload.setSizeMax(20 * 1024); upload.setFileSizeMax(10 * 1024); List<FileItem> items; try { items = upload.parseRequest(request); } catch (FileUploadException e) { throw new RequestMappingException("", e); } return items.stream().map(item -> { String key = item.getFieldName(); if (item.isFormField()) { String value = item.getString(); return new SimpleKeyValue<String, Object>(key, value); } else { return new SimpleKeyValue<String, Object>(key, item); } }).collect(Collectors.toMap( SimpleKeyValue::getKey, SimpleKeyValue::getValue )); }
/** * {@inheritDoc} * <pre> * BLOBに保存するためヘッダ情報 + ファイル本体の形式の一時ファイルを作成します。 * </pre> */ @Override protected File makeTempFromFileItem(final FileItem fileItem) throws Exception { // log.error("makeTempFromFileItem", new Exception()); String fileName = FileUtil.getFileName(fileItem.getName()); long length = fileItem.getSize(); File file = null; InputStream is = fileItem.getInputStream(); try { file = this.makeBlobTempFile(fileName, length, is); } finally { is.close(); } // this.tempFile = file; return file; }
/** * Retrieve a parameter passed to the servlet as part of a multi part content. * * @param parameter * the name of the parameter to be retrieved * @param requestFilter * filter used to validate the input against list of allowed inputs * @return String containing the value of the parameter. Empty string if the content is not * multipart or the parameter is not found. */ public String getMultiParameter(String parameter, RequestFilter requestFilter) { if (!isMultipart || items == null) return ""; Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField() && item.getFieldName().equals(parameter)) { try { String value = item.getString("UTF-8"); filterRequest(requestFilter, value); return value; } catch (Exception ex) { ex.printStackTrace(); return ""; } } } return ""; }
/** * Retrieve a set of values belonging to a parameter passed to the servlet as part of a multi part * content. * * @param parameter * The name of the parameter to be retrieved. * @param requestFilter * filter used to validate the input against list of allowed inputs * @return String array containing the values of the parameter. Empty string if the content is not * multipart. */ public String[] getMultiParameters(String parameter, RequestFilter requestFilter) { if (!isMultipart || items == null) return null; Iterator<FileItem> iter = items.iterator(); Vector<String> result = new Vector<String>(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField() && item.getFieldName().equals(parameter)) { try { String value = item.getString("UTF-8"); filterRequest(requestFilter, value); result.addElement(value); } catch (Exception ex) { } } } String[] strResult = new String[result.size()]; result.copyInto(strResult); return strResult; }
@Override public void onPost() { JSON jo = new JSON(); User me = this.getUser(); if (me != null) { // String access = Module.home.get("upload.require.access"); FileItem file = this.getFile("file"); store(me.getId(), file, jo); } else { this.set(X.ERROR, HttpServletResponse.SC_UNAUTHORIZED); jo.put(X.MESSAGE, lang.get("login.required")); } // /** // * test // */ // jo.put("error", "error"); this.response(jo); }
public List<FileItem> checkContentType(HttpServletRequest request, String encoding){ if(null != fileTypes && fileTypes.size() > 0){ FileUpload fileUpload = prepareFileUpload(encoding); try { List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request); for (FileItem item : fileItems) { if(!item.isFormField()) { //必须是文件 log.debug("client want to upload file with name: " + item.getName()); log.debug("client want to upload file with type: " + item.getContentType()); if (!fileTypes.contains(AppFileUtils.getFileExtByName(item.getName()))) { for(String fileType : fileTypes){ log.error("Allowd fileType is: "+fileType); } throw new NotAllowUploadFileTypeException("Not allow upload file type exception occur, client upload type is: "+AppFileUtils.getFileExtByName(item.getName())); } } } return fileItems; } catch (FileUploadException e) { throw new NotAllowUploadFileTypeException("Not allow upload file type exception occur... \r\n" + e.getMessage()); } } return null; }
public static void store(DocFile doc, FileItem fileItem) { String fullPath = getFullPath(doc); File file = new File(fullPath); if (file.isFile()) { log.warn("File " + fullPath + " exists: will be overwritten!"); } File dir = file.getParentFile(); if (!dir.exists()) { dir.mkdirs(); log.info("Creating directory " + dir.getAbsolutePath()); } try { fileItem.write(file); } catch (Exception ex) { log.fatal(ex); } }
public Hashtable getHashtable(HttpServletRequest request) throws FileUploadException, IOException { Hashtable ht = new Hashtable(); DiskFileUpload upload = new DiskFileUpload(); List fileItems = upload.parseRequest(request); Iterator iter = fileItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { ht.put(item.getFieldName(), item.getString()); } else { if (item.getName().equals("")) { //ht.put(item.getFieldName(), null); } else if (item.getSize() == 0) { //ht.put(item.getFieldName(), null); } else { ht.put(item.getFieldName(), item.getInputStream()); } } } return ht; }
/** * 解析上传域 * * @param item 文件对象 * @return {@link FileFormResult} * @throws IOException IO异常 */ private FileFormResult processUploadedFile(FileItem item) throws IOException { String name = item.getName(); String fileSuffix = FilenameUtils.getExtension(name); if (CollectionUtils.isNotEmpty(allowedSuffixList) && !allowedSuffixList.contains(fileSuffix)) { throw new NotAllowedUploadException(String.format("上传文件格式不正确,fileName=%s,allowedSuffixList=%s", name, allowedSuffixList)); } FileFormResult file = new FileFormResult(); file.setFieldName(item.getFieldName()); file.setFileName(name); file.setContentType(item.getContentType()); file.setSizeInBytes(item.getSize()); //如果未设置上传路径,直接保存到项目根目录 if (Strings.isNullOrEmpty(baseDir)) { baseDir = request.getRealPath("/"); } File relativePath = new File(SEPARATOR + DateFormatUtils.format(new Date(), "yyyyMMdd") + file.getFileName()); FileCopyUtils.copy(item.getInputStream(), new FileOutputStream(relativePath)); file.setSaveRelativePath(relativePath.getAbsolutePath()); return file; }
/** * <p> Adds a file parameter to the set of file parameters for this * request and also to the list of all parameters. </p> * * @param item The file item for the parameter to add. */ protected void addFileParameter(FileItem item) { FormFile formFile = new CommonsFormFile(item); String name = item.getFieldName(); if (elementsFile.containsKey(name)) { Object o = elementsFile.get(name); if (o instanceof List) { ((List)o).add(formFile); } else { List list = new ArrayList(); list.add((FormFile)o); list.add(formFile); elementsFile.put(name, list); elementsAll.put(name, list); } } else { elementsFile.put(name, formFile); elementsAll.put(name, formFile); } }
/** * バックアップファイルを解凍します。 * @param fileItem バックアップファイル。 * @return 展開されたディレクトリのパス。 * @throws Exception 例外。 */ public String unpackRestoreFile(final FileItem fileItem) throws Exception { InputStream is = fileItem.getInputStream(); String ret = null; try { File bkdir = new File(DataFormsServlet.getTempDir() + "/restore"); if (!bkdir.exists()) { bkdir.mkdirs(); } Path backup = FileUtil.createTempDirectory(bkdir.getAbsolutePath(), "restore"); FileUtil.unpackZipFile(is, backup.toString()); ret = backup.toString(); } finally { is.close(); } return ret; }
protected void processFileField(FileItem item) { LOG.debug("Item is a file upload"); // Skip file uploads that don't have a file name - meaning that no file was selected. if (item.getName() == null || item.getName().trim().length() < 1) { LOG.debug("No file has been uploaded for the field: {}", item.getFieldName()); return; } List<FileItem> values; if (files.get(item.getFieldName()) != null) { values = files.get(item.getFieldName()); } else { values = new ArrayList<>(); } values.add(item); files.put(item.getFieldName(), values); }
/** * extracts attachments from the http request. * * @param httpRequest * request containing attachments DefaultMultipartHttpServletRequest is supported * @param request * {@link Request} * @return ids of extracted attachments * @throws MaxLengthReachedException * attachment size is to large * @throws IOException * throws exception if problems during attachments accessing occurred * @throws FileUploadException * Exception. * @throws AuthorizationException * in case there is no authenticated user */ private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest, Request request) throws MaxLengthReachedException, FileUploadException, IOException, AuthorizationException { List<AttachmentResource> result = new ArrayList<AttachmentResource>(); if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) { FileItemFactory factory = new DiskFileItemFactory(); FileUpload upload = new FileUpload(factory); List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest)); for (FileItem file : items) { if (!file.isFormField()) { AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(), AttachmentStatus.UPLOADED); AttachmentResourceHelper.checkAttachmentSize(file); attachmentTo.setMetadata(new ContentMetadata()); attachmentTo.getMetadata().setFilename(getFileName(file.getName())); attachmentTo.getMetadata().setContentSize(file.getSize()); result.add(persistAttachment(request, attachmentTo)); } } } return result; }
/** * リストアを行います。 * @param p パラメータ。 * @return 処理結果。 * @throws Exception 例外。 */ @WebMethod public Response restore(final Map<String, Object> p) throws Exception { this.methodStartLog(log, p); Response resp = null; List<ValidationError> list = this.validate(p); if (list.size() == 0) { FileItem fi = (FileItem) p.get("backupFile"); String path = this.unpackRestoreFile(fi); TableManagerDao dao = new TableManagerDao(this); List<String> flist = FileUtil.getFileList(path); for (String fn: flist) { if (Pattern.matches(".*\\.data\\.json$", fn)) { log.debug("fn=" + fn); String classname = fn.substring(path.length() + 1).replaceAll("[\\\\/]", ".").replaceAll("\\.data\\.json$", ""); log.debug("classname=" + classname); dao.importData(classname, path); } } resp = new JsonResponse(JsonResponse.SUCCESS, MessagesUtil.getMessage(this.getPage(), "message.restored")); } else { resp = new JsonResponse(JsonResponse.INVALID, list); } this.methodFinishLog(log, resp); return resp; }
public void cleanUp() { Set<String> names = files.keySet(); for (String name : names) { List<FileItem> items = files.get(name); for (FileItem item : items) { if (LOG.isDebugEnabled()) { String msg = LocalizedTextUtil.findText(this.getClass(), "struts.messages.removing.file", Locale.ENGLISH, "no.message.found", new Object[]{name, item}); LOG.debug(msg); } if (!item.isInMemory()) { item.delete(); } } } }
/** * Process multipart request item as regular form field. The name and value * of each regular form field will be added to the given parameterMap. * * @param formField The form field to be processed. * @param parameterMap The parameterMap to be used for the HttpServletRequest. */ private void processFormField(FileItem formField, Map<String, String[]> parameterMap) { String name = formField.getFieldName(); String value = formField.getString(); String[] values = parameterMap.get(name); if (values == null) { // Not in parameter map yet, so add as new value. parameterMap.put(name, new String[]{value}); } else { // Multiple field values, so add new value to existing array. int length = values.length; String[] newValues = new String[length + 1]; System.arraycopy(values, 0, newValues, 0, length); newValues[length] = value; parameterMap.put(name, newValues); } }
/** * extracts attachments from the http request. * * @param httpRequest * request containing attachments DefaultMultipartHttpServletRequest is supported * @param request * {@link Request} * @return ids of extracted attachments * @throws MaxLengthReachedException * attachment size is to large * @throws IOException * throws exception if problems during attachments accessing occurred * @throws FileUploadException * Exception. * @throws AuthorizationException * in case there is no authenticated user */ private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest, Request request) throws MaxLengthReachedException, FileUploadException, IOException, AuthorizationException { List<AttachmentResource> result = new ArrayList<AttachmentResource>(); if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) { FileItemFactory factory = new DiskFileItemFactory(); FileUpload upload = new FileUpload(factory); List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest)); for (FileItem file : items) { if (!file.isFormField()) { AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(), AttachmentStatus.UPLOADED); AttachmentResourceHelper.assertAttachmentSize(file.getContentType(), file.getSize(), false); attachmentTo.setMetadata(new ContentMetadata()); attachmentTo.getMetadata().setFilename(getFileName(file.getName())); attachmentTo.getMetadata().setContentSize(file.getSize()); result.add(persistAttachment(request, attachmentTo)); } } } return result; }
@SuppressWarnings("unchecked") public Map<String, Object> parseMultipart(HttpServletRequest request) throws IOException, ServletException { ServletFileUpload upload = new ServletFileUpload(_uploadItemFactory); List<FileItem> items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { throw new ServletException(e); } Map<String, Object> params = new HashMap<String, Object>(); for (FileItem item : items) { if (item.isFormField()) params.put(item.getFieldName(), item.getString()); else params.put(item.getFieldName(), item); } return params; }
FileData(FileItem item) { this.fileName = item.getName(); this.type = item.getContentType(); this.data = item.get(); if(fileName != null) { int i = fileName.lastIndexOf("/"); if(i>0) { fileName = fileName.substring(i+1); } else { i = fileName.lastIndexOf("\\"); if(i>0) { fileName = fileName.substring(i+1); } } } this.item = item; }
/** * extracts attachments from the http request. * * @param httpRequest * request containing attachments DefaultMultipartHttpServletRequest is supported * @param request * {@link Request} * @return ids of extracted attachments * @throws IOException * throws exception if problems during attachments accessing occurred * @throws FileUploadException * Exception. * @throws AttachmentIsEmptyException * Thrown, when the attachment is of zero size. * @throws AuthorizationException * in case there is no authenticated user */ private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest, Request request) throws FileUploadException, IOException, AttachmentIsEmptyException, AuthorizationException { List<AttachmentResource> result = new ArrayList<>(); if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) { FileItemFactory factory = new DiskFileItemFactory(); FileUpload upload = new FileUpload(factory); List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest)); for (FileItem file : items) { if (!file.isFormField()) { AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(), AttachmentStatus.UPLOADED); AttachmentResourceHelper.assertAttachmentSize(file.getContentType(), file.getSize(), false); attachmentTo.setMetadata(new ContentMetadata()); attachmentTo.getMetadata().setFilename(getFileName(file.getName())); attachmentTo.getMetadata().setContentSize(file.getSize()); result.add(persistAttachment(request, attachmentTo)); } } } return result; }
/** * extracts attachments from the http request. * * @param httpRequest * request containing attachments DefaultMultipartHttpServletRequest is supported * @param request * {@link Request} * @return ids of extracted attachments * @throws MaxLengthReachedException * attachment size is to large * @throws IOException * throws exception if problems during attachments accessing occurred * @throws FileUploadException * Exception. * @throws AttachmentIsEmptyException * Thrown, when the attachment is of zero size. * @throws AuthorizationException * in case there is no authenticated user */ private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest, Request request) throws MaxLengthReachedException, FileUploadException, IOException, AttachmentIsEmptyException, AuthorizationException { List<AttachmentResource> result = new ArrayList<AttachmentResource>(); if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) { FileItemFactory factory = new DiskFileItemFactory(); FileUpload upload = new FileUpload(factory); List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest)); for (FileItem file : items) { if (!file.isFormField()) { AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(), AttachmentStatus.UPLOADED); AttachmentResourceHelper.assertAttachmentSize(file.getContentType(), file.getSize(), false); attachmentTo.setMetadata(new ContentMetadata()); attachmentTo.getMetadata().setFilename(getFileName(file.getName())); attachmentTo.getMetadata().setContentSize(file.getSize()); result.add(persistAttachment(request, attachmentTo)); } } } return result; }
@RequestMapping(method = RequestMethod.POST) protected ModelAndView handleRequestInternal(HttpServletRequest request) throws Exception { String username = securityService.getCurrentUsername(request); // Check that we have a file upload request. if (!ServletFileUpload.isMultipartContent(request)) { throw new Exception("Illegal request."); } Map<String, Object> map = new HashMap<String, Object>(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<?> items = upload.parseRequest(request); // Look for file items. for (Object o : items) { FileItem item = (FileItem) o; if (!item.isFormField()) { String fileName = item.getName(); byte[] data = item.get(); if (StringUtils.isNotBlank(fileName) && data.length > 0) { createAvatar(fileName, data, username, map); } else { map.put("error", new Exception("Missing file.")); LOG.warn("Failed to upload personal image. No file specified."); } break; } } map.put("username", username); map.put("avatar", settingsService.getCustomAvatar(username)); return new ModelAndView("avatarUploadResult","model",map); }
@RequestMapping(method = RequestMethod.POST) protected String handlePost(RedirectAttributes redirectAttributes, HttpServletRequest request ) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); try { if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<?> items = upload.parseRequest(request); for (Object o : items) { FileItem item = (FileItem) o; if ("file".equals(item.getFieldName()) && !StringUtils.isBlank(item.getName())) { if (item.getSize() > MAX_PLAYLIST_SIZE_MB * 1024L * 1024L) { throw new Exception("The playlist file is too large. Max file size is " + MAX_PLAYLIST_SIZE_MB + " MB."); } String playlistName = FilenameUtils.getBaseName(item.getName()); String fileName = FilenameUtils.getName(item.getName()); String format = StringUtils.lowerCase(FilenameUtils.getExtension(item.getName())); String username = securityService.getCurrentUsername(request); Playlist playlist = playlistService.importPlaylist(username, playlistName, fileName, item.getInputStream(), null); map.put("playlist", playlist); } } } } catch (Exception e) { map.put("error", e.getMessage()); } redirectAttributes.addFlashAttribute("model", map); return "redirect:importPlaylist"; }