List of usage examples for org.springframework.web.multipart MultipartFile getOriginalFilename
@Nullable String getOriginalFilename();
From source file:com.dlshouwen.tdjs.picture.controller.TdjsPictureController.java
/** * /* w w w.j av a2 s .com*/ * * @param picture * @param bindingResult ? * @param request * @return ajax? * @throws Exception */ @RequestMapping(value = "/ajaxAdd", method = RequestMethod.POST) @ResponseBody public void ajaxAddPicture(@Valid Picture picture, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) throws Exception { // AJAX? AjaxResponse ajaxResponse = new AjaxResponse(); // ??zz if (bindingResult.hasErrors()) { ajaxResponse.bindingResultHandler(bindingResult); // ? LogUtils.updateOperationLog(request, OperationType.INSERT, "???" + AjaxResponse.getBindingResultMessage(bindingResult) + ""); response.setContentType("text/html;charset=utf-8"); JSONObject obj = JSONObject.fromObject(ajaxResponse); response.getWriter().write(obj.toString()); return; } String path = ""; MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile multipartFile = multipartRequest.getFile("picture"); if (multipartFile != null && StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) { //?? JSONObject jobj = FileUploadClient.upFile(request, multipartFile.getOriginalFilename(), multipartFile.getInputStream()); if (null != jobj && jobj.getString("responseMessage").equals("OK")) { path = jobj.getString("fpath"); } } // ???? SessionUser sessionUser = (SessionUser) request.getSession().getAttribute(CONFIG.SESSION_USER); String userId = sessionUser.getUser_id(); String userName = sessionUser.getUser_name(); Date nowDate = new Date(); // ? picture.setPicture_id(new GUID().toString()); picture.setCreate_time(nowDate); picture.setUser_id(userId); picture.setUser_name(userName); path = path.replaceAll("\\\\", "/"); picture.setPath(path); // dao.insertPicture(picture); // ???? ajaxResponse.setSuccess(true); ajaxResponse.setSuccessMessage("??"); //? Map map = new HashMap(); map.put("URL", "tdjs/tdjsPicture/picture"); ajaxResponse.setExtParam(map); // ? LogUtils.updateOperationLog(request, OperationType.INSERT, "?" + picture.getPicture_id()); response.setContentType("text/html;charset=utf-8"); JSONObject obj = JSONObject.fromObject(ajaxResponse); response.getWriter().write(obj.toString()); }
From source file:org.dawnsci.marketplace.controllers.ExtendedRestApiController.java
/** * Uploads a screenshot to the solution and updates the solution data with * the name of the file being uploaded. Returns a <b>403 Forbidden</b> if * the logged in user is not the owner of the solution. *//*from ww w. ja v a 2 s . c o m*/ @PreAuthorize("hasRole('UPLOAD')") @RequestMapping(value = "/upload-screenshot") public ResponseEntity<String> uploadScreenshot(Principal principal, @RequestParam("id") Long id, @RequestParam("file") MultipartFile file) throws Exception { // verify that we have the correct owner Account account = accountRepository.findOne(principal.getName()); if (!canEdit(principal, id)) { return new ResponseEntity<String>("Logged in user is not the owner of the solution", HttpStatus.FORBIDDEN); } fileService.saveSolutionFile(id, file); // get solution and update with new information Node node = marketplaceDAO.getSolution(id); node.setScreenshot(file.getOriginalFilename()); Object result = marketplaceDAO.saveOrUpdateSolution(node, account); if (result instanceof Node) { return new ResponseEntity<String>(MarketplaceSerializer.serialize((Node) result), HttpStatus.OK); } else { return new ResponseEntity<String>((String) result, HttpStatus.INTERNAL_SERVER_ERROR); } }
From source file:data.repository.pragma.DataObjectController.java
@RequestMapping(value = "/DO/upload", method = RequestMethod.POST) @ResponseBody//from ww w .ja va 2s.c o m public MessageResponse DOupload(@RequestParam(value = "data", required = true) MultipartFile file, @RequestParam(value = "metadata", required = true) String metadata) { try { // Create metadata DBObject from input DBObject metadataObject = (DBObject) JSON.parse(metadata); // Ingest multipart file into inputstream byte[] byteArr = file.getBytes(); InputStream inputStream = new ByteArrayInputStream(byteArr); String file_name = file.getOriginalFilename(); String content_type = file.getContentType(); // Connect to MongoDB and use GridFS to store metadata and data // Return created DO internal id in stagingDB String id = Staging_repository.addDO(inputStream, file_name, content_type, metadataObject); MessageResponse response = new MessageResponse(true, id); return response; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); MessageResponse response = new MessageResponse(false, null); return response; } }
From source file:com.baidu.upload.controller.ImageController.java
@RequestMapping(value = "/upload", method = RequestMethod.POST) public @ResponseBody Map<String, Object> upload(MultipartHttpServletRequest request, HttpServletResponse response, Integer reqid) { log.debug("uploadPost called"); System.out.println("id" + reqid); //????/*from ww w . j a va 2 s . c o m*/ Iterator<String> itr = request.getFileNames(); MultipartFile mpf; List<Image> list = new LinkedList<Image>(); InputStream is = null; List<File> newfiles = new ArrayList<File>(); while (itr.hasNext()) { mpf = request.getFile(itr.next()); //?uuid?? String newFilenameBase = UUID.randomUUID().toString(); //???? String originalFileExtension = mpf.getOriginalFilename() .substring(mpf.getOriginalFilename().lastIndexOf(".")); //??? String newFilename = newFilenameBase + originalFileExtension; //? //String storageDirectory = request.getSession().getServletContext().getRealPath("/")+"pic"; //fileUploadDirectory = storageDirectory; String storageDirectory = fileUploadDirectory; String contentType = mpf.getContentType(); // File newFile = new File(storageDirectory + "/" + newFilename); try { //?? is = mpf.getInputStream(); byte[] bytes = FileCopyUtils.copyToByteArray(is); // mpf.transferTo(newFile); // BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 290); //??uuid-thumbnail.png String thumbnailFilename = newFilenameBase + "-thumbnail.png"; // File thumbnailFile = new File(storageDirectory + "/" + thumbnailFilename); ImageIO.write(thumbnail, "png", thumbnailFile); //image Image image = new Image(); //?blob image.setImgblob(bytes); //image.setName(mpf.getOriginalFilename()); image.setName(newFilename); image.setThumbnailFilename(thumbnailFilename); image.setNewFilename(newFilename); image.setContentType(contentType); image.setSize(mpf.getSize()); image.setThumbnailSize(thumbnailFile.length()); //?id int id = this.imageService.findId(); image.setId(id); //url image.setUrl("../img/picture/" + image.getId() + ".do"); image.setThumbnailUrl("../img/thumbnail/" + image.getId() + ".do"); image.setDeleteUrl("../img/delete/" + image.getId() + ".do"); image.setDeleteType("DELETE"); //? image.setReqid(reqid); image = imageService.create(image); newfiles.add(newFile); //?? list.add(image); } catch (IOException e) { log.error("Could not upload file " + mpf.getOriginalFilename(), e); } finally { IOUtils.closeQuietly(is); } } Map<String, Object> files = new HashMap<String, Object>(); files.put("files", list); return files; }
From source file:controllers.ProcessController.java
@RequestMapping("management/staffs/edit") public ModelAndView editStaff(@RequestParam("id") String id, @RequestParam("name") String name, @RequestParam("gender") String genderString, @RequestParam("birthday") String birthdayString, @RequestParam("avatar") MultipartFile avatar, @RequestParam("email") String email, @RequestParam("phone") String phone, @RequestParam("salary") String salaryString, @RequestParam("note") String notes, @RequestParam("depart") String departId) throws IOException { String avatarFileName = ""; if (!avatar.isEmpty()) { String avatarPath = context.getRealPath("/resources/images/" + avatar.getOriginalFilename()); avatar.transferTo(new File(avatarPath)); avatarFileName = new File(avatarPath).getName(); }/* w w w.ja v a 2 s . c o m*/ StaffsDAO staffsDAO = new StaffsDAO(); staffsDAO.editStaff(id, name, genderString, birthdayString, avatarFileName, email, phone, salaryString, notes, departId); return new ModelAndView("redirect:../staffs.htm"); }
From source file:org.fenixedu.qubdocs.ui.documenttemplates.AcademicServiceRequestTemplateController.java
@Atomic public AcademicServiceRequestTemplate createAcademicServiceRequestTemplate( org.fenixedu.commons.i18n.LocalizedString name, org.fenixedu.commons.i18n.LocalizedString description, java.util.Locale language, org.fenixedu.academic.domain.serviceRequests.ServiceRequestType serviceRequestType, org.fenixedu.academic.domain.degree.DegreeType degreeType, org.fenixedu.academic.domain.Degree degree, org.fenixedu.academic.domain.degreeStructure.ProgramConclusion programConclusion, MultipartFile documentTemplateFile) throws IOException { AcademicServiceRequestTemplate academicServiceRequestTemplate = AcademicServiceRequestTemplate.create(name, description, language, serviceRequestType, degreeType, programConclusion, degree); DocumentTemplateFile.create(academicServiceRequestTemplate, documentTemplateFile.getOriginalFilename(), documentTemplateFile.getBytes()); return academicServiceRequestTemplate; }
From source file:mx.edu.um.mateo.inventario.web.ProductoController.java
@RequestMapping(value = "/actualiza", method = RequestMethod.POST) public String actualiza(HttpServletRequest request, @Valid Producto producto, BindingResult bindingResult, Errors errors, Model modelo, RedirectAttributes redirectAttributes, @RequestParam(value = "imagen", required = false) MultipartFile archivo) { if (bindingResult.hasErrors()) { log.error("Hubo algun error en la forma, regresando"); return "inventario/producto/edita"; }/* w w w. j a v a 2s . c o m*/ try { if (archivo != null && !archivo.isEmpty()) { log.debug("SUBIENDO ARCHIVO: {}", archivo.getOriginalFilename()); Imagen imagen = new Imagen(archivo.getOriginalFilename(), archivo.getContentType(), archivo.getSize(), archivo.getBytes()); producto.getImagenes().add(imagen); } Usuario usuario = ambiente.obtieneUsuario(); producto = productoDao.actualiza(producto, usuario); } catch (IOException e) { log.error("No se pudo actualizar el producto", e); errors.rejectValue("imagenes", "problema.con.imagen.message", new String[] { archivo.getOriginalFilename() }, null); Map<String, Object> params = new HashMap<>(); params.put("almacen", request.getSession().getAttribute("almacenId")); params.put("reporte", true); params = tipoProductoDao.lista(params); modelo.addAttribute("tiposDeProducto", params.get("tiposDeProducto")); return "inventario/producto/edita"; } catch (ConstraintViolationException e) { log.error("No se pudo actualizar el producto", e); errors.rejectValue("nombre", "campo.duplicado.message", new String[] { "nombre" }, null); Map<String, Object> params = new HashMap<>(); params.put("almacen", request.getSession().getAttribute("almacenId")); params.put("reporte", true); params = tipoProductoDao.lista(params); modelo.addAttribute("tiposDeProducto", params.get("tiposDeProducto")); return "inventario/producto/edita"; } redirectAttributes.addFlashAttribute("message", "producto.actualizado.message"); redirectAttributes.addFlashAttribute("messageAttrs", new String[] { producto.getNombre() }); return "redirect:/inventario/producto/ver/" + producto.getId(); }
From source file:com.vsquaresystem.safedeals.rawmarketprice.RawMarketPriceService.java
@Transactional(readOnly = false) public Boolean insertAttachments(MultipartFile attachmentMultipartFile) throws JsonProcessingException, IOException { logger.info("attachmentMultipartFile in service Line31{}", attachmentMultipartFile); System.out.println("attachmentMultipartFile" + attachmentMultipartFile); File outputFile = attachmentUtils.storeAttachmentByAttachmentType( attachmentMultipartFile.getOriginalFilename(), attachmentMultipartFile.getInputStream(), AttachmentUtils.AttachmentType.RAW_MARKET_PRICE); return outputFile.exists(); }
From source file:com.dlshouwen.wzgl.content.controller.ArticleController.java
/** * /*from ww w .ja v a2 s .c om*/ * * @param album * @param bindingResult * @return ajax? * @throws Exception */ @RequestMapping(value = "/editAlbum", method = RequestMethod.POST) public void editArtAlbum(@Valid Album album, HttpServletRequest request, BindingResult bindingResult, HttpServletResponse response) throws Exception { // AJAX? AjaxResponse ajaxResponse = new AjaxResponse(); // ?? if (bindingResult.hasErrors()) { ajaxResponse.bindingResultHandler(bindingResult); // ? LogUtils.updateOperationLog(request, OperationType.UPDATE, "id" + album.getAlbum_id() + "??" + album.getAlbum_name() + "?" + AjaxResponse.getBindingResultMessage(bindingResult) + ""); response.setContentType("text/html;charset=utf-8"); JSONObject obj = JSONObject.fromObject(ajaxResponse); response.getWriter().write(obj.toString()); return; } MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile multipartFile = multipartRequest.getFile("picture"); String fileName = multipartFile.getOriginalFilename(); //? String path = null; if (null != multipartFile && StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) { JSONObject jobj = FileUploadClient.upFile(request, multipartFile.getOriginalFilename(), multipartFile.getInputStream()); if (jobj.getString("responseMessage").equals("OK")) { path = jobj.getString("fpath"); } } /* if (fileName.trim().length() > 0) { int pos = fileName.lastIndexOf("."); fileName = fileName.substring(pos); String fileDirPath = request.getSession().getServletContext().getRealPath("/"); String path = fileDirPath.substring(0, fileDirPath.lastIndexOf(File.separator)) + CONFIG.UPLOAD_PIC_PATH; Date date = new Date(); fileName = String.valueOf(date.getTime()) + fileName; File file = new File(path); if (!file.exists()) { file.mkdirs(); } file = new File(path + "/" + fileName); if (!file.exists()) { file.createNewFile(); } path = path + "/" + fileName; FileOutputStream fos = null; InputStream s = null; try { fos = new FileOutputStream(file); s = multipartFile.getInputStream(); byte[] buffer = new byte[1024]; int read = 0; while ((read = s.read(buffer)) != -1) { fos.write(buffer, 0, read); } fos.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { fos.close(); } if (s != null) { s.close(); } } path = path.replaceAll("\\\\", "/"); album.setAlbum_coverpath(path); } */ if (null != path) { album.setAlbum_coverpath(path); } // ???? Date nowDate = new Date(); // ? album.setAlbum_updatedate(nowDate); album.setAlbum_flag("1"); // albumDao.updateAlbum(album); // ???? ajaxResponse.setSuccess(true); ajaxResponse.setSuccessMessage("??"); //URL?? Map map = new HashMap(); map.put("URL", "wzgl/article/article"); ajaxResponse.setExtParam(map); // ? LogUtils.updateOperationLog(request, OperationType.UPDATE, "id" + album.getAlbum_id() + "??" + album.getAlbum_name()); response.setContentType("text/html;charset=utf-8"); JSONObject obj = JSONObject.fromObject(ajaxResponse); response.getWriter().write(obj.toString()); }
From source file:de.hska.ld.core.controller.UserController.java
@Secured(Core.ROLE_USER) @RequestMapping(method = RequestMethod.POST, value = "/avatar") public Callable uploadAvatar(@RequestParam MultipartFile file) { return () -> { String name = file.getOriginalFilename(); if (!file.isEmpty()) { userService.uploadAvatar(file, name); return new ResponseEntity<>(HttpStatus.OK); } else {//from w ww .j a v a2 s .co m throw new ValidationException("file"); } }; }