List of usage examples for org.springframework.web.multipart MultipartFile getOriginalFilename
@Nullable String getOriginalFilename();
From source file:eionet.webq.web.controller.WebQProxyDelegation.java
/** * The method proxies multipart POST requests. If the request target is CDR envelope, then USerFile authorization info is used. * * @param uri the address to forward the request * @param fileId UserFile id stored in session * @param multipartRequest file part in multipart request * @return response from remote host// ww w .j a va2 s. c om * @throws URISyntaxException provide URI is incorrect * @throws IOException could not read file from request */ @RequestMapping(value = "/restProxyFileUpload", method = RequestMethod.POST, produces = "text/html;charset=utf-8") @ResponseBody public String restProxyFileUpload(@RequestParam("uri") String uri, @RequestParam int fileId, MultipartHttpServletRequest multipartRequest) throws URISyntaxException, IOException { UserFile file = userFileHelper.getUserFile(fileId, multipartRequest); if (!multipartRequest.getFileNames().hasNext()) { throw new IllegalArgumentException("File not found in multipart request."); } Map<String, String[]> parameters = multipartRequest.getParameterMap(); // limit request to one file String fileName = multipartRequest.getFileNames().next(); MultipartFile multipartFile = multipartRequest.getFile(fileName); HttpHeaders authorization = new HttpHeaders(); if (file != null && StringUtils.startsWith(uri, file.getEnvelope())) { authorization = envelopeService.getAuthorizationHeader(file); } HttpHeaders fileHeaders = new HttpHeaders(); fileHeaders.setContentDispositionFormData("file", multipartFile.getOriginalFilename()); fileHeaders.setContentType(MediaType.valueOf(multipartFile.getContentType())); MultiValueMap<String, Object> request = new LinkedMultiValueMap<String, Object>(); byte[] content = multipartFile.getBytes(); request.add("file", new HttpEntity<byte[]>(content, fileHeaders)); for (Map.Entry<String, String[]> parameter : parameters.entrySet()) { if (!parameter.getKey().equals("uri") && !parameter.getKey().equals("fileId") && !parameter.getKey().equals("sessionid") && !parameter.getKey().equals("restricted")) { request.add(parameter.getKey(), new HttpEntity<String>(StringUtils.defaultString(parameter.getValue()[0]))); } } HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>( request, authorization); LOGGER.info("/restProxyFileUpload [POST] uri=" + uri); return restTemplate.postForObject(uri, requestEntity, String.class); }
From source file:org.chimi.s4s.controller.FileUploadController.java
@RequestMapping(value = "/upload/{serviceId}", method = RequestMethod.POST) public String upload(@RequestParam(value = "file", required = false) MultipartFile userUploadFile, @PathVariable("serviceId") String serviceId, HttpServletRequest request, ModelMap model) { String resultViewName = "uploadResult"; if (userUploadFile == null || userUploadFile.isEmpty()) { model.put(resultViewName, UploadResultResponse.createNoFileResult()); return resultViewName; }//from w w w . j av a2 s . c o m // ? ? File tempFile = null; try { tempFile = getTemporaryFile(userUploadFile); } catch (Exception ex) { logger.error("fail to get temp file for " + userUploadFile.getOriginalFilename(), ex); model.put(resultViewName, UploadResultResponse.createErrorResult()); return resultViewName; } // ?? ? try { String fileName = extractFileName(userUploadFile.getOriginalFilename()); String mimeType = getMimeType(fileName); UploadResult uploadResult = saveTemporaryFileToFileService(userUploadFile, serviceId, fileName, mimeType, tempFile); String[] urls = createUrl(uploadResult, request); model.put(resultViewName, UploadResultResponse.createSuccessResult(uploadResult, urls[0], urls[1])); return resultViewName; } catch (Exception ex) { logger.error("fail to save file to storage" + userUploadFile.getOriginalFilename(), ex); model.put(resultViewName, UploadResultResponse.createErrorResult()); return resultViewName; } finally { deleteTempFile(tempFile); } }
From source file:com.all_widgets.fileservice.FileService.java
/** * ***************************************************************************** * NAME: uploadFile//from w ww. j a va 2 s . c om * DESCRIPTION: * The FileUpload widget automatically calls this method whenever the user selects a new file. * <p/> * PARAMS: * file : multipart file to be uploaded. * relativePath : This is the relative path where file will be uploaded. * <p/> * RETURNS FileUploadResponse. * This has the following fields * Path: tells the client where the file was stored so that the client can identify the file to the server * Name: tells the client what the original name of the file was so that any * communications with the end user can use a filename familiar to that user. * Type: returns type information to the client, based on filename extensions (.txt, .pdf, .gif, etc...) * ****************************************************************************** */ public FileUploadResponse[] uploadFile(MultipartFile[] files, String relativePath, HttpServletRequest httpServletRequest) { List<FileUploadResponse> wmFileList = new ArrayList<>(); File outputFile = null; for (MultipartFile file : files) { try { outputFile = fileServiceManager.uploadFile(file, relativePath, uploadDirectory); // Create WMFile object wmFileList.add(new FileUploadResponse( WMRuntimeUtils.getContextRelativePath(outputFile, httpServletRequest, relativePath), outputFile.getName(), outputFile.length(), true, "")); } catch (Exception e) { wmFileList.add(new FileUploadResponse(null, file.getOriginalFilename(), 0, false, e.getMessage())); } } return wmFileList.toArray(new FileUploadResponse[wmFileList.size()]); }
From source file:cn.lhfei.fu.service.impl.HomeworkBaseServiceImpl.java
/** * // w ww.j a v a2 s . com * * @see cn.lhfei.fu.service.HomeworkBaseService#update(cn.lhfei.fu.web.model.HomeworkBaseModel) */ @Override public boolean update(HomeworkBaseModel model, String userType) throws NullPointerException { OutputStream out = null; BufferedOutputStream bf = null; Date currentTime = new Date(); List<MultipartFile> files = model.getFiles(); try { HomeworkBase base = homeworkBaseDAO.find(model.getBaseId()); base.setModifyTime(currentTime); base.setActionType("" + OperationTypeEnum.SC.getCode()); base.setOperationTime(currentTime); homeworkBaseDAO.save(base); // update homework_base info int num = 1; for (MultipartFile file : files) {// save archive file if (file.getSize() > 0) { String filePath = filePathBuilder.buildFullPath(model, model.getStudentName()); String fileName = filePathBuilder.buildFileName(model, model.getStudentName(), num); String[] names = file.getOriginalFilename().split("[.]"); String fileType = names[names.length - 1]; String fullPath = filePath + File.separator + fileName + "." + fileType; out = new FileOutputStream(new File(fullPath)); bf = new BufferedOutputStream(out); IOUtils.copyLarge(file.getInputStream(), bf); HomeworkArchive archive = new HomeworkArchive(); archive.setArchiveName(fileName); archive.setArchivePath(fullPath); archive.setCreateTime(currentTime); archive.setModifyTime(currentTime); archive.setName(model.getName()); archive.setStudentBaseId(model.getStudentBaseId()); archive.setHomeworkBaseId(model.getBaseId()); /*archive.setHomeworkBase(base);*/ archive.setStudentName(model.getStudentName()); archive.setStudentId(model.getStudentId()); // ? if (userType != null && userType.equals(UserTypeEnum.STUDENT.getCode())) { archive.setStatus("" + ApproveStatusEnum.DSH.getCode()); } else if (userType != null && userType.equals(UserTypeEnum.TEACHER.getCode())) { archive.setStatus("" + ApproveStatusEnum.DSH.getCode()); } else if (userType != null && userType.equals(UserTypeEnum.ADMIN.getCode())) { archive.setStatus("" + ApproveStatusEnum.YSH.getCode()); } homeworkArchiveDAO.save(archive); // auto increment archives number. num++; } } } catch (IOException e) { log.error(e.getMessage(), e); } catch (NullPointerException e) { log.error("File name arguments missed.", e); throw new NullPointerException(e.getMessage()); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException e) { log.error(e.getMessage(), e); } } if (bf != null) { try { bf.flush(); bf.close(); } catch (IOException e) { log.error(e.getMessage(), e); } } } return false; }
From source file:com.dlshouwen.wzgl.picture.controller.PictureController.java
/** * // ww w .ja v a2 s. c o m * * @param picture * @param bindingResult ? * @param request * @return ajax? * @throws Exception */ @RequestMapping(value = "/ajaxAdd", method = RequestMethod.POST) 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); //? Map map = new HashMap(); map.put("URL", basePath + "picture"); ajaxResponse.setExtParam(map); // ? 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; } 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, fileName, multipartFile.getInputStream()); if (jobj.getString("responseMessage").equals("OK")) { path = jobj.getString("fpath"); } } /* 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(); } } */ if (StringUtils.isNotEmpty(path)) { // ???? 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", basePath + "picture"); ajaxResponse.setExtParam(map); } else { // ???? ajaxResponse.setError(true); ajaxResponse.setErrorMessage("?"); } // ? 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()); return; }
From source file:com.fileupload.fileservice.FileService.java
/** * ***************************************************************************** * NAME: uploadFile//from www . j av a 2 s .c o m * DESCRIPTION: * The FileUpload widget automatically calls this method whenever the user selects a new file. * <p/> * PARAMS: * file : multipart file to be uploaded. * relativePath : This is the relative path where file will be uploaded. * <p/> * RETURNS FileUploadResponse. * This has the following fields * Path: tells the client where the file was stored so that the client can identify the file to the server * Name: tells the client what the original name of the file was so that any * communications with the end user can use a filename familiar to that user. * Type: returns type information to the client, based on filename extensions (.txt, .pdf, .gif, etc...) * ****************************************************************************** */ public FileUploadResponse[] uploadFile(MultipartFile[] files, String relativePath, HttpServletRequest httpServletRequest) { if (StringUtils.isNotBlank(relativePath) && !relativePath.endsWith("/")) { relativePath = relativePath + "/"; } List<FileUploadResponse> wmFileList = new ArrayList<>(); File outputFile = null; for (MultipartFile file : files) { try { outputFile = fileServiceManager.uploadFile(file, relativePath, uploadDirectory); // Create WMFile object wmFileList.add(new FileUploadResponse( WMRuntimeUtils.getContextRelativePath(outputFile, httpServletRequest, relativePath), outputFile.getName(), outputFile.length(), true, "")); } catch (Exception e) { wmFileList.add(new FileUploadResponse(null, file.getOriginalFilename(), 0, false, e.getMessage())); } } return wmFileList.toArray(new FileUploadResponse[wmFileList.size()]); }
From source file:eionet.transfer.dao.UploadsServiceSwift.java
@Override public void storeFile(MultipartFile myFile, String fileId, int fileTTL) throws IOException { if (swiftUsername == null) { System.out.println("Swift username is not configured"); }/*from ww w .j a v a 2 s . c om*/ assert swiftUsername != null; if (config == null) { login(); } StoredObject swiftObject = container.getObject(fileId); swiftObject.uploadObject(myFile.getInputStream()); if (myFile.getContentType() != null) { swiftObject.setContentType(myFile.getContentType()); } Map<String, Object> metadata = new HashMap<String, Object>(); if (myFile.getOriginalFilename() != null) { metadata.put("filename", myFile.getOriginalFilename()); } if (myFile.getContentType() != null) { metadata.put("content-type", myFile.getContentType()); } swiftObject.setMetadata(metadata); swiftObject.saveMetadata(); //swiftObject.setDeleteAt(Date date); }
From source file:com.test.mvc.FileUploadController.java
@RequestMapping(value = "/generateOutput", method = RequestMethod.POST) public String generateOutput(@RequestParam("file") MultipartFile file, ModelMap model) { MonkParser monkParser = new MonkParser(); MasterTemplateUtil masterTemplate = new MasterTemplateUtil(); masterTemplate.buildMasterForAllSegement(); masterTemplate.buildMSHSegment();//from w w w .j a v a2 s .co m masterTemplate.buildEVNSegment(); masterTemplate.buildPIDSegment(); masterTemplate.buildPV1Segment(); masterTemplate.buildPV2Segment(); masterTemplate.buildDG1Segment(); masterTemplate.buildIN1Segment(); masterTemplate.buildNTESegment(); masterTemplate.buildOBRSegment(); masterTemplate.buildORCSegment(); masterTemplate.buildOBXSegment(); String fileName = file.getOriginalFilename(); String filePath = System.getProperty("java.io.tmpdir") + "\\" + fileName; try { file.transferTo(new File(filePath)); } catch (IOException | IllegalStateException ex) { Logger.getLogger(FileUploadController.class.getName()).log(Level.SEVERE, null, ex); } monkParser.setFilePath(filePath); String resultPath = monkParser.getResultPath(); TemplateGenerator templateGenerator = new TemplateGenerator(resultPath); try { monkParser.readFile(); monkParser.constructFinalLogic(masterTemplate); templateGenerator.generateTemplateWithHL7Standards(masterTemplate); } catch (FileNotFoundException ex) { System.out.println("Was Not able to find file: " + ex); } catch (IOException ex) { System.out.println("Reading File has some difficulties: " + ex); } model.addAttribute("fileName", "Legacy_" + fileName.split("\\.")[0] + "_TR"); model.addAttribute("resultPath", templateGenerator.getDestinationFilePath()); model.addAttribute("contentType", file.getContentType()); return "generateOutput"; }
From source file:com.springsource.html5expense.controller.ExpenseController.java
@RequestMapping(value = "/createNewExpenseReport", method = RequestMethod.POST) public String createNewExpenseReport(@RequestParam("file") MultipartFile file, HttpServletRequest request) { String description = request.getParameter("description"); String expenseTypeVal = request.getParameter("expenseTypeId"); ExpenseType expenseType = expenseTypeService.getExpenseTypeById(new Long(expenseTypeVal)); String amount = request.getParameter("amount"); Date expenseDate = new Date(); Double amountVal = new Double(amount); User user = (User) request.getSession().getAttribute("user"); String fileName = ""; String contentType = ""; if (file != null) { try {/*from ww w . j a v a2 s . c om*/ fileName = file.getOriginalFilename(); contentType = file.getContentType(); Attachment attachment = new Attachment(fileName, contentType, file.getBytes()); attachmentService.save(attachment); Long id = expenseService.createExpense(description, expenseType, expenseDate, amountVal, user, attachment); } catch (Exception e) { } } return "redirect:/"; }
From source file:com.smart.smartrestfulw.controller.FileDepotController.java
/** * ??/*from w ww .ja v a 2 s. c o m*/ * * @param formFileData * @param strJson * @param isModify ??? * @return */ private String SaveUpLoadFile(List<MultipartFile> uploadFiles, FileDepotParamModel paramModel, boolean isModify) throws Exception { String strSvcFileLocalName = null, strUpFileName = null, strTempFilePath = null; StringBuffer sbTemp = new StringBuffer(); StringBuffer sbFilePathTemp = new StringBuffer(); boolean bSvcFileExist = false; Set<String> setStrSqls = new HashSet<String>(); ExecuteResultParam resultParam = null; DepotFileDetailModel tempFileDetailModel = null; int saveFlag = 1; if (paramModel == null) { return responseFormat.formationResultToString(ResponseResultCode.ErrorParam, "paramError"); } SignInformationModel signModel = SignCommon.verifySign(paramModel.getToken(), false); if (signModel == null) { return responseFormat.formationResultToString(ResponseResultCode.ErrorSignToken, "no authorize"); } try { for (MultipartFile tempFile : uploadFiles) { strUpFileName = tempFile.getOriginalFilename(); // root/rsid/date(yymmddhh)/Type // sbFilePathTemp.append(paramModel.rsid); sbTemp.append(DeployInfo.GetDeployFilePath()).append(File.separator).append(paramModel.rsid); FileHelper.CheckFileExist(sbTemp.toString()); // sbFilePathTemp.append(File.separator).append(UtileSmart.getCurrentDate()); sbTemp.append(File.separator).append(UtileSmart.getCurrentDate()); FileHelper.CheckFileExist(sbTemp.toString()); tempFileDetailModel = paramModel.getFileDetailModel(strUpFileName); if (tempFileDetailModel == null) { return responseFormat.formationResultToString(ResponseResultCode.ErrorParam, "param error."); // return formationResult.formationResult(ResponseResultCode.Error, new ExecuteResultParam(String.format("? %s?", strUpFileName), paramModel.toStringInformation())); } //? (File.separator) if (tempFileDetailModel.fileOwnType.indexOf(File.separator) > 0) { return responseFormat.formationResultToString(ResponseResultCode.ErrorFileType, "file type error"); // return formationResult.formationResult(ResponseResultCode.Error, new ExecuteResultParam(String.format("? %s?", strUpFileName), paramModel.toStringInformation())); //return formationResult.formationResult(ResponseResultCode.Error, new ExecuteResultParam(String.format("??", strUpFileName), paramModel.toStringInformation())); } sbFilePathTemp.append(File.separator).append(tempFileDetailModel.fileOwnType); sbTemp.append(File.separator).append(tempFileDetailModel.fileOwnType); FileHelper.CheckFileExist(sbTemp.toString()); //? sbFilePathTemp.append(File.separator).append(strUpFileName).toString(); strSvcFileLocalName = sbTemp.append(File.separator).append(strUpFileName).toString(); bSvcFileExist = FileHelper.CheckFileExist(strSvcFileLocalName, false); if (bSvcFileExist && isModify == false) { return responseFormat.formationResultToString(ResponseResultCode.ErrorFileExist, "file exist"); //return formationResult.formationResult(ResponseResultCode.Error, new ExecuteResultParam(String.format("????%s", strUpFileName), paramModel.toStringInformation())); } //?? ownid fpath??????? resultParam = DBHelper.ExecuteSqlOnceSelect(DeployInfo.MasterRSID, String.format( "SELECT COUNT(*) AS ROWSCOUNT FROM FILEDEPOT WHERE OWNID<>'%s' AND FPATH='%s'", paramModel.ownid, sbFilePathTemp.toString())); if (resultParam.ResultCode != 0) { return responseFormat.formationResultToString(ResponseResultCode.ErrorDB, resultParam.errMsg); //return formationResult.formationResult(ResponseResultCode.Error, new ExecuteResultParam(String.format("????%s : Msg : %s", strUpFileName, resultParam.errMsg), paramModel.toStringInformation())); } //ROWSCOUNT ?0?? ROWSCOUNT ?0??????? if (resultParam.ResultJsonObject != null) { if (Integer.parseInt(resultParam.ResultJsonObject.getJSONObject(DeployInfo.ResultDataTag) .getString("ROWSCOUNT")) > 0) { return responseFormat.formationResultToString(ResponseResultCode.ErrorFileRepeat, "file binded "); //return formationResult.formationResult(ResponseResultCode.Error, new ExecuteResultParam(String.format("%s,?????????????", strUpFileName), paramModel.toStringInformation())); } } tempFile.transferTo(new File(strSvcFileLocalName)); //?????? tempFileDetailModel.fileLocalPath = strSvcFileLocalName; //?sql???? if (isModify) { //todo ?sql?? // 1,?? // 2? uuid ???? //3? uuid ? setStrSqls.add(String.format( "INSERT INTO FILEDEPOT (FID,FNAME,FPATH,FSUMMARY,OWNID,OWNFILETYPE) VALUES ('%s','%s','%s','%s','%s','%s')", UUID.randomUUID().toString(), strUpFileName, sbFilePathTemp.toString(), "md5", paramModel.ownid, tempFileDetailModel.fileOwnType)); } else { setStrSqls.add(String.format( "INSERT INTO FILEDEPOT (FID,FNAME,FPATH,FSUMMARY,OWNID,OWNFILETYPE) VALUES ('%s','%s','%s','%s','%s','%s')", UUID.randomUUID().toString(), strUpFileName, sbFilePathTemp.toString(), "md5", paramModel.ownid, tempFileDetailModel.fileOwnType)); } sbTemp.delete(0, sbTemp.length()); sbFilePathTemp.delete(0, sbFilePathTemp.length()); } //??? resultParam = DBHelper.ExecuteSql(DeployInfo.MasterRSID, setStrSqls); if (resultParam.ResultCode >= 0) { saveFlag = 0; //???? resultParam = SelectDepotFileByOwn(new FileDepotParamModel(paramModel.ownid)); //return formationResult.formationResult(ResponseResultCode.Success, new ExecuteResultParam(resultParam.ResultJsonObject)); return responseFormat.formationSuccessResultToString(resultParam.ResultJsonObject); } else { return responseFormat.formationResultToString(ResponseResultCode.ErrorDB, resultParam.errMsg); //return formationResult.formationResult(ResponseResultCode.Error, new ExecuteResultParam(String.format("??%s", resultParam.errMsg), paramModel.toStringInformation())); } } catch (Exception e) { return responseFormat.formationResultToString(ResponseResultCode.ErrorDB, e); // return formationResult.formationResult(ResponseResultCode.Error, new ExecuteResultParam(e.getLocalizedMessage(), paramModel.toStringInformation(), e)); } finally { if (saveFlag == 1) { DeleteFile(paramModel.fileDetaile); } UtileSmart.FreeObjects(strSvcFileLocalName, strUpFileName, strTempFilePath, sbTemp, sbFilePathTemp, setStrSqls, resultParam, paramModel, tempFileDetailModel); } }