/* @RequestMapping(value = "/uploadfile.html", method = RequestMethod.GET) public String uploadFile(){ return "uploadfile"; } */ @RequestMapping(value = "/uploadfile.html", method = RequestMethod.POST) public String processUploadPreview( @RequestParam("file") MultipartFile file, @RequestParam("id") Integer recordId, Map<String, Object> respMap) { Record record = recordService.getRecord(recordId); respMap.put("record", record); if (record == null) { // respMap.put("errMesg", "Incorect or not available record"); return "redirect:records.html"; } respMap.put("id", recordId); if (file.getSize() > 5242880) { respMap.put("errMesg", "Max file size 5MB"); return "redirect:editrecord.html"; } if (file.getName().equals("")) { respMap.put("errMesg", "File not selected"); return "redirect:editrecord.html"; } File newFile = new File(); newFile.setRecord(record); newFile.setFilename(file.getOriginalFilename()); newFile.setType(file.getName()); try { newFile.setFile(file.getBytes()); fileService.addFilele(newFile); } catch (Exception e) { respMap.put("errMesg", "Server error"); e.printStackTrace(); return "redirect:editrecord.html"; } return "redirect:editrecord.html"; }
/** * 설문템플릿를 수정처리 한다. * * @param multiRequest * @param searchVO * @param commandMap * @param qustnrTmplatManageVO * @param bindingResult * @param model * @return "/uss/olp/qtm/EgovQustnrTmplatManageModifyActor" * @throws Exception */ @RequestMapping(value = "/uss/olp/qtm/EgovQustnrTmplatManageModifyActor.do") public String QustnrTmplatManageModifyActor( final MultipartHttpServletRequest multiRequest, @ModelAttribute("searchVO") ComDefaultVO searchVO, Map commandMap, @ModelAttribute("qustnrTmplatManageVO") QustnrTmplatManageVO qustnrTmplatManageVO, BindingResult bindingResult, ModelMap model) throws Exception { // 0. Spring Security 사용자권한 처리 Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated(); if (!isAuthenticated) { model.addAttribute("message", egovMessageSource.getMessage("fail.common.login")); return "uat/uia/EgovLoginUsr"; } // 로그인 객체 선언 LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser(); // 서버 validate 체크 beanValidator.validate(qustnrTmplatManageVO, bindingResult); if (bindingResult.hasErrors()) { model.addAttribute( "resultList", egovQustnrTmplatManageService.selectQustnrTmplatManageDetail(qustnrTmplatManageVO)); return "/uss/olp/qtm/EgovQustnrTmplatManageModify"; } // 아이디 설정 qustnrTmplatManageVO.setFrstRegisterId((String) loginVO.getUniqId()); qustnrTmplatManageVO.setLastUpdusrId((String) loginVO.getUniqId()); final Map<String, MultipartFile> files = multiRequest.getFileMap(); if (!files.isEmpty()) { for (MultipartFile file : files.values()) { System.out.println("getName =>" + file.getName()); System.out.println("getOriginalFilename =>" + file.getOriginalFilename()); // log.info("getOriginalFilename =>" + file.getOriginalFilename() ); if (file.getName().equals("qestnrTmplatImage") && !file.getOriginalFilename().equals("")) { qustnrTmplatManageVO.setQestnrTmplatImagepathnm(file.getBytes()); } } } egovQustnrTmplatManageService.updateQustnrTmplatManage(qustnrTmplatManageVO); return "redirect:/uss/olp/qtm/EgovQustnrTmplatManageList.do"; }
@RequestMapping( value = "/upLoad/{file}", method = {RequestMethod.GET, RequestMethod.POST}) @ResponseBody public String upload(MultipartHttpServletRequest request) { System.out.println("开始"); String path = request.getSession().getServletContext().getRealPath("upload"); Iterator<?> iterator = request.getFileNames(); String result = "上传失败"; while (iterator.hasNext()) { MultipartFile multipartFile = request.getFile((String) iterator.next()); Long size = multipartFile.getSize(); Float mb = (float) (size / (1024 * 1024)); if (mb < 20) { String name = multipartFile.getName(); Version v = FileUtil.saveUploadFile(multipartFile, path, name, "upload"); if (v != null) { result = "上传成功"; } else { result = "上传失败"; } } else { result = "文件大小超过20MB"; } } return new JsonMapper().toJson(result); }
@RequestMapping(value = "/my/upload", method = RequestMethod.POST) public @ResponseBody Map upload( @RequestParam(value = "upfile", required = true) MultipartFile filedata, HttpSession session, Model model) { ContextUtil.setCurrUser((User) session.getAttribute("user")); Map<String, String> rtn = Maps.newHashMap(); try { String path = ImageUtils.uploadImages( filedata.getOriginalFilename(), filedata.getContentType(), filedata.getBytes()); Media media = new Media(); media.setAddress(path); media.setStatus(1); media.setUploadDate(new Date()); media.setType(1); media.setUserId(ContextUtil.getCurrUser().getId()); media.setName(filedata.getOriginalFilename()); media.setLength(filedata.getBytes().length); mediaService.addMedia(media); rtn.put("state", "FAILED"); if (path != null) { rtn.put("state", "SUCCESS"); rtn.put("name", filedata.getName()); rtn.put("originalName", filedata.getOriginalFilename()); rtn.put("size", String.valueOf(filedata.getSize())); rtn.put("type", filedata.getContentType()); rtn.put("url", ImageUtils.IMAGE_DOMAIN_WITH_PROTOCOL + path); } } catch (IOException e) { rtn.put("state", e.getLocalizedMessage()); } return rtn; }
@RequestMapping(value = "/save", method = RequestMethod.POST) public String save( @Valid @ModelAttribute("document") Document document, BindingResult result, @RequestParam("file") MultipartFile file) { if (result.hasErrors()) { return "doc/documents.tiles"; } System.out.println("Name:" + document.getName()); System.out.println("Desc:" + document.getDescription()); System.out.println("File:" + file.getName()); System.out.println("ContentType:" + file.getContentType()); try { Blob blob = Hibernate.createBlob(file.getInputStream()); document.setFilename(file.getOriginalFilename()); document.setContent(blob); document.setContentType(file.getContentType()); } catch (IOException e) { e.printStackTrace(); } try { documentService.save(document); } catch (Exception e) { e.printStackTrace(); } return "redirect:/doc/index"; }
/** * multipartFile To ByteArray * * @param oMultipartFile * @return * @throws java.io.IOException */ public static ByteArrayOutputStream multipartFileToByteArray( MultipartFile oMultipartFile, String sFileNameReal) throws IOException { LOG.debug("(sFileNameReal={})", sFileNameReal); // String sFilename = new String(file.getOriginalFilename().getBytes(), "Cp1251");//UTF-8 // LOG.debug("(sFilename={})", sFilename); String sFilenameEncoded = new String( oMultipartFile.getOriginalFilename().getBytes(Charset.forName("UTF-8"))); // UTF-8 LOG.debug("(sFilenameEncoded={})", sFilenameEncoded); /* String sFilename2 = new String(file.getOriginalFilename().getBytes(), "UTF-8");//UTF-8 LOG.debug("(sFilename2={})", sFilename2); String sFilename3 = new String(file.getOriginalFilename().getBytes(Charset.forName("Cp1251")));//UTF-8 LOG.debug("(sFilename3={})", sFilename3); String sFilename4 = new String(file.getOriginalFilename().getBytes());//UTF-8 LOG.debug("(sFilename4={})", sFilename4); String sFilename0 = file.getOriginalFilename();//UTF-8 LOG.debug("(sFilename0={})", sFilename0); //sFilename = Renamer.sRenamed(sFilename0); String sFilenameNew0 = Renamer.sRenamed(sFilename0); LOG.debug("(sFilenameNew0={})", sFilenameNew0); String sFilenameNew1 = Renamer.sRenamed(sFilename1); LOG.debug("(sFilenameNew1={})", sFilenameNew1); String sFilenameNew2 = Renamer.sRenamed(sFilename2); LOG.debug("(sFilenameNew2={})", sFilenameNew2); String sFilenameNew3 = Renamer.sRenamed(sFilename3); LOG.debug("(sFilenameNew3={})", sFilenameNew3); String sFilenameNew4 = Renamer.sRenamed(sFilename4); LOG.debug("(sFilenameNew4={})", sFilenameNew4); //sFilename=sFilenameNew; LOG.debug("(sFilename(new)={})", sFilename);*/ ByteArrayMultipartFile oByteArrayMultipartFile = new ByteArrayMultipartFile( oMultipartFile.getBytes(), oMultipartFile.getName(), sFileNameReal == null ? sFilenameEncoded : sFileNameReal, oMultipartFile.getContentType()); ByteArrayOutputStream oByteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream oObjectOutputStream = new ObjectOutputStream(oByteArrayOutputStream); oObjectOutputStream.writeObject(oByteArrayMultipartFile); oObjectOutputStream.flush(); oObjectOutputStream.close(); return oByteArrayOutputStream; }
@RequestMapping( value = "/applyeffect", method = RequestMethod.POST, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) public @ResponseBody byte[] applyEffect( @RequestParam("userid") String userId, @RequestParam("type") int effectType, @RequestParam("file") MultipartFile file) { try { byte[] bytes = file.getBytes(); File temp = new File(file.getName()); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(temp)); stream.write(bytes); stream.close(); File newFile = null; if (effectType == 1) { newFile = ImageUtils.applyTint(userId, temp, 50); } else if (effectType == 2) { newFile = ImageUtils.applyEffect(userId, temp, 128); } else if (effectType == 3) { newFile = ImageUtils.applyBlackWhiteEffect(userId, temp, 128); } // java.nio.file.Path p= Paths.get(newFile.toURI()); /*FileInputStream input=new FileInputStream(newFile); response.setContentType("image/jpg"); response.setContentLength(42707); response.getOutputStream().write(IOUtils.toByteArray(input));*/ FileInputStream input = new FileInputStream(newFile); byte[] data = IOUtils.toByteArray(input); /*File ff=new File("D:/selfy/test.jpg"); FileOutputStream out=new FileOutputStream(ff); out.write(data, 0, data.length); out.close();*/ return data; } catch (Exception e) { System.out.println(e.toString()); return null; } }
@RequestMapping(value = "upload", method = RequestMethod.POST) public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile $file) { System.out.println("uploadFile" + $file.getName()); try { String file_name = $file.getOriginalFilename(); String file_path = UPLOAD_PATH + File.separator + file_name; BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(file_path))); stream.write($file.getBytes()); stream.close(); } catch (Exception e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(HttpStatus.OK); }
/** * 설문템플릿를 등록 처리 한다. / 등록처리 * * @param multiRequest * @param searchVO * @param qustnrTmplatManageVO * @param model * @return "/uss/olp/qtm/EgovQustnrTmplatManageRegistActor" * @throws Exception */ @RequestMapping(value = "/uss/olp/qtm/EgovQustnrTmplatManageRegistActor.do") public String QustnrTmplatManageRegistActor( final MultipartHttpServletRequest multiRequest, @ModelAttribute("searchVO") ComDefaultVO searchVO, QustnrTmplatManageVO qustnrTmplatManageVO, ModelMap model) throws Exception { // 0. Spring Security 사용자권한 처리 Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated(); if (!isAuthenticated) { model.addAttribute("message", egovMessageSource.getMessage("fail.common.login")); return "uat/uia/EgovLoginUsr"; } // 로그인 객체 선언 LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser(); // 아이디 설정 qustnrTmplatManageVO.setFrstRegisterId((String) loginVO.getUniqId()); qustnrTmplatManageVO.setLastUpdusrId((String) loginVO.getUniqId()); final Map<String, MultipartFile> files = multiRequest.getFileMap(); if (!files.isEmpty()) { for (MultipartFile file : files.values()) { // log.info("getName =>" + file.getName() ); // log.info("getOriginalFilename =>" + file.getOriginalFilename() ); if (file.getName().equals("qestnrTmplatImage")) { qustnrTmplatManageVO.setQestnrTmplatImagepathnm(file.getBytes()); } } } // log.info("qestnrTmplatImagepathnm =>" + qustnrTmplatManageVO.getQestnrTmplatImagepathnm() ); egovQustnrTmplatManageService.insertQustnrTmplatManage(qustnrTmplatManageVO); return "redirect:/uss/olp/qtm/EgovQustnrTmplatManageList.do"; }
/** * Add a file to this request. The parameter name from the multipart form is taken from the {@link * MultipartFile#getName()}. * * @param file multipart file to be added */ public void addFile(MultipartFile file) { Assert.notNull(file, "MultipartFile must not be null"); this.multipartFiles.add(file.getName(), file); }
/** 导入Excel 解析 */ @RequestMapping("/user/importMsgExcel/{type}") @ResponseBody public Map<String, Object> importExcel( HttpServletRequest request, @RequestParam("myFile") MultipartFile myFile, @PathVariable("type") int type) { try { logger.info("myFile:" + myFile.getName()); HSSFWorkbook wookbook = new HSSFWorkbook(myFile.getInputStream()); // 只读取sheet1 HSSFSheet sheet = wookbook.getSheet("Sheet1"); int rows = sheet.getLastRowNum(); // Excel行数 String mobileStr = ""; for (int i = 1; i <= rows; i++) { // 读取左上端单元格 HSSFRow row = sheet.getRow(i); // 行不为空 if (row != null) { // **读取cell** HSSFCell cell = row.getCell((short) 0); if (cell != null) { switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_FORMULA: break; case HSSFCell.CELL_TYPE_NUMERIC: DecimalFormat df = new DecimalFormat("#"); mobileStr += df.format(cell.getNumericCellValue()) + ","; break; case HSSFCell.CELL_TYPE_STRING: mobileStr += cell.getStringCellValue().trim() + ","; break; default: break; } } } } // 获得页面的 if (request.getParameter("numerStr") != null && request.getParameter("numerStr") != "") { mobileStr += request.getParameter("numerStr"); } Map<String, Object> returnMap = null; if (type == 1) { // 短信页面 returnMap = checkMobile(mobileStr); if (Boolean.parseBoolean(returnMap.get("flag").toString()) == false) { this.setJson(false, returnMap.get("errorMobile").toString(), ""); return json; } else { this.setJson(true, "", returnMap.get("mobileList")); } } else { // 邮箱页面 returnMap = checkEmail(mobileStr); if (Boolean.parseBoolean(returnMap.get("flag").toString()) == false) { this.setJson(false, returnMap.get("errorMessage").toString(), ""); return json; } else { this.setJson(true, "", returnMap.get("returnList")); } } } catch (Exception e) { logger.error("importExcel", e); this.setJson(false, "Excel导入错误", null); return json; } return json; }
@ActionMapping(params = "javax.portlet.action=uploadXDR") public void response(MultipartActionRequest request, ActionResponse response) throws IOException { JSONArray fileJson; JSONObject jsonResponseBody; if (this.props == null) { this.loadProperties(); } // handle the files: response.setRenderParameter("javax.portlet.action", "uploadXDR"); MultipartFile file = request.getFile("file"); String endpoint = request.getParameter("wsdlLocation"); String fromDirectAddress = request.getParameter("fromDirectAddress"); if (fromDirectAddress == null || fromDirectAddress.trim().equals("")) { fromDirectAddress = "*****@*****.**"; } String toDirectAddress = request.getParameter("toDirectAddress"); if (toDirectAddress == null || toDirectAddress.trim().equals("")) { toDirectAddress = "*****@*****.**"; } String messageType = request.getParameter("messageType"); String encodedFile = Base64.encodeBase64String(file.getBytes()); fileJson = new JSONArray(); jsonResponseBody = new JSONObject(); String xdrResponse = null; if (messageType.equalsIgnoreCase("full")) { xdrResponse = XDR.sendValidFullXDRMessage( endpoint, encodedFile, file.getName(), toDirectAddress, fromDirectAddress, endpoint); } else { xdrResponse = XDR.sendValidMinimalXDRMessage( endpoint, encodedFile, file.getName(), toDirectAddress, fromDirectAddress, endpoint); } logger.info(xdrResponse); try { JSONObject jsono = new JSONObject(); jsono.put("name", file.getOriginalFilename()); jsono.put("size", file.getSize()); fileJson.put(jsono); // handle the data jsonResponseBody.put("IsSuccess", "true"); jsonResponseBody.put("ErrorMessage", "Message Sent Successfully!"); jsonResponseBody.put("xdrResponse", xdrResponse); statisticsManager.addXdrReceive( endpoint, fromDirectAddress, toDirectAddress, messageType, false, true, false); } catch (Exception e) { // statisticsManager.addCcdaValidation(ccda_type_value, false, false, false, true); statisticsManager.addXdrReceive( endpoint, fromDirectAddress, toDirectAddress, messageType, false, false, true); throw new RuntimeException(e); } xdrReceiveResults.setFileJson(fileJson); xdrReceiveResults.setJsonResponseBody(jsonResponseBody); }
public CommentAttachment(MultipartFile multipartFile) throws IOException { this.name = multipartFile.getName(); this.type = multipartFile.getContentType(); this.contents = multipartFile.getBytes(); this.description = "The description of " + this.name; }
@ApiOperation( value = "Upload a file with certified products", notes = "Accepts a CSV file with very specific fields to create pending certified products. " + " The user uploading the file must have ROLE_ACB_ADMIN or ROLE_ACB_STAFF " + " and administrative authority on the ACB(s) specified in the file.") @RequestMapping( value = "/upload", method = RequestMethod.POST, produces = "application/json; charset=utf-8") public @ResponseBody PendingCertifiedProductResults upload( @RequestParam("file") MultipartFile file) throws ValidationException, MaxUploadSizeExceededException { if (file.isEmpty()) { throw new ValidationException("You cannot upload an empty file!"); } if (!file.getContentType().equalsIgnoreCase("text/csv") && !file.getContentType().equalsIgnoreCase("application/vnd.ms-excel")) { throw new ValidationException("File must be a CSV document."); } List<PendingCertifiedProductDetails> uploadedProducts = new ArrayList<PendingCertifiedProductDetails>(); BufferedReader reader = null; CSVParser parser = null; try { reader = new BufferedReader(new InputStreamReader(file.getInputStream())); parser = new CSVParser(reader, CSVFormat.EXCEL); List<CSVRecord> records = parser.getRecords(); if (records.size() <= 1) { throw new ValidationException( "The file appears to have a header line with no other information. Please make sure there are at least two rows in the CSV file."); } Set<String> handlerErrors = new HashSet<String>(); List<PendingCertifiedProductEntity> cpsToAdd = new ArrayList<PendingCertifiedProductEntity>(); // parse the entire file into groups of records, one group per product CSVRecord heading = null; Set<String> uniqueIdsFromFile = new HashSet<String>(); Set<String> duplicateIdsFromFile = new HashSet<String>(); List<CSVRecord> rows = new ArrayList<CSVRecord>(); for (int i = 0; i < records.size(); i++) { CSVRecord currRecord = records.get(i); if (heading == null && !StringUtils.isEmpty(currRecord.get(1)) && currRecord.get(1).equals("RECORD_STATUS__C")) { // have to find the heading first heading = currRecord; } else if (heading != null) { if (!StringUtils.isEmpty(currRecord.get(0))) { String currUniqueId = currRecord.get(0); String currStatus = currRecord.get(1); if (currStatus.equalsIgnoreCase("NEW")) { if (!currUniqueId.contains("XXXX") && uniqueIdsFromFile.contains(currUniqueId)) { handlerErrors.add( "Multiple products with unique id " + currUniqueId + " were found in the file."); duplicateIdsFromFile.add(currUniqueId); } else { uniqueIdsFromFile.add(currUniqueId); // parse the previous recordset if (rows.size() > 0) { try { CertifiedProductUploadHandler handler = uploadHandlerFactory.getHandler(heading, rows); PendingCertifiedProductEntity pendingCp = handler.handle(); cpsToAdd.add(pendingCp); } catch (InvalidArgumentsException ex) { handlerErrors.add(ex.getMessage()); } } rows.clear(); } } if (!duplicateIdsFromFile.contains(currUniqueId)) { rows.add(currRecord); } } } // add the last object if (i == records.size() - 1 && !rows.isEmpty()) { try { CertifiedProductUploadHandler handler = uploadHandlerFactory.getHandler(heading, rows); PendingCertifiedProductEntity pendingCp = handler.handle(); cpsToAdd.add(pendingCp); } catch (InvalidArgumentsException ex) { handlerErrors.add(ex.getMessage()); } } } if (handlerErrors.size() > 0) { throw new ValidationException(handlerErrors, null); } Set<String> allErrors = new HashSet<String>(); for (PendingCertifiedProductEntity cpToAdd : cpsToAdd) { if (cpToAdd.getErrorMessages() != null && cpToAdd.getErrorMessages().size() > 0) { allErrors.addAll(cpToAdd.getErrorMessages()); } } if (allErrors.size() > 0) { throw new ValidationException(allErrors, null); } else { for (PendingCertifiedProductEntity cpToAdd : cpsToAdd) { try { PendingCertifiedProductDTO pendingCpDto = pcpManager.createOrReplace(cpToAdd.getCertificationBodyId(), cpToAdd); PendingCertifiedProductDetails details = new PendingCertifiedProductDetails(pendingCpDto); uploadedProducts.add(details); } catch (EntityCreationException ex) { logger.error("Error creating pending certified product: " + cpToAdd.getUniqueId()); } catch (EntityRetrievalException ex) { logger.error("Error retreiving pending certified product.", ex); } } } } catch (IOException ioEx) { logger.error("Could not get input stream for uploaded file " + file.getName()); throw new ValidationException( "Could not get input stream for uploaded file " + file.getName()); } finally { try { parser.close(); } catch (Exception ignore) { } try { reader.close(); } catch (Exception ignore) { } } PendingCertifiedProductResults results = new PendingCertifiedProductResults(); results.getPendingCertifiedProducts().addAll(uploadedProducts); return results; }
private ServletRequest prepareServletRequest( Object target, NativeWebRequest request, MethodParameter parameter) { String modelPrefixName = parameter.getParameterAnnotation(FormModel.class).value(); HttpServletRequest nativeRequest = (HttpServletRequest) request.getNativeRequest(); MultipartRequest multipartRequest = WebUtils.getNativeRequest(nativeRequest, MultipartRequest.class); MockHttpServletRequest mockRequest = null; if (multipartRequest != null) { MockMultipartHttpServletRequest mockMultipartRequest = new MockMultipartHttpServletRequest(); for (MultipartFile file : multipartRequest.getFileMap().values()) { mockMultipartRequest.addFile( new MultipartFileWrapper(getNewParameterName(file.getName(), modelPrefixName), file)); } mockRequest = mockMultipartRequest; } else { mockRequest = new MockHttpServletRequest(); } for (Entry<String, String> entry : getUriTemplateVariables(request).entrySet()) { String parameterName = entry.getKey(); String value = entry.getValue(); if (isFormModelAttribute(parameterName, modelPrefixName)) { mockRequest.setParameter(getNewParameterName(parameterName, modelPrefixName), value); } } for (Object parameterEntry : nativeRequest.getParameterMap().entrySet()) { Entry<String, String[]> entry = (Entry<String, String[]>) parameterEntry; String parameterName = entry.getKey(); String[] value = entry.getValue(); if (isFormModelAttribute(parameterName, modelPrefixName)) { mockRequest.setParameter(getNewParameterName(parameterName, modelPrefixName), value); } } return mockRequest; }