/** * Im头像上传 * * @param file * @return * @throws Exception */ @RequestMapping("uploadImHeadPortrait") @ResponseBody public PageData uploadImHeadPortrait(MultipartFile[] file) throws Exception { PageData pd = fileUpd(file); Object content = pd.get("content"); PageData returnPd = new PageData(); if (pd.getString("state").equals("200")) { String path = (String) ((HashMap) ((List) content).get(0)).get("path"); String sltpath = (String) ((HashMap) ((List) content).get(0)).get("sltpath"); PageData returnPd1 = new PageData(); returnPd1.put("src", path); returnPd1.put("srcSlt", sltpath); returnPd.put("code", "0"); returnPd.put("msg", "success"); returnPd.put("data", returnPd1); return WebResult.requestSuccess(returnPd); } else { return WebResult.requestFailed(500, "服务器错误", pd.get("content")); } }
public static UserFile of(MultipartFile file, User user) { UserFile userFile = new UserFile(); userFile.setName(file.getOriginalFilename()); userFile.setSize(file.getSize()); userFile.setUploader(user); userFile.setPath(uuid() + "." + FilenameUtils.getExtension(file.getOriginalFilename())); String mimeType = file.getContentType(); String type = mimeType.split("/")[0]; if (type.equalsIgnoreCase("image")) { userFile.setFileType(FileType.IMAGE); } // TODO set filetype to DOC or ETC ZonedDateTime utc = ZonedDateTime.now(ZoneOffset.UTC); userFile.setUploadedAt(Date.from(utc.toInstant())); return userFile; }
@RequestMapping(value = "/{id}/uploadAvatar", method = RequestMethod.POST) @ApiOperation(value = "Add new upload Avatar") public String uploadAvatar(@ApiParam(value = "user Id", required = true) @PathVariable("id") Integer id, @ApiParam(value = "Image File", required = true) @RequestPart("file") MultipartFile file) { String contentType = file.getContentType(); if (!FileUploadUtil.isValidImageFile(contentType)) { return "Invalid image File! Content Type :-" + contentType; } File directory = new File(AVATAR_UPLOAD.getValue()); if (!directory.exists()) { directory.mkdir(); } File f = new File(userService.getAvatarUploadPath(id)); try (FileOutputStream fos = new FileOutputStream(f)) { byte[] imageByte = file.getBytes(); fos.write(imageByte); return "Success"; } catch (Exception e) { return "Error saving avatar for User " + id + " : " + e; } }
public player(String playerId, String firstName, String lastName, String fullName, String alias, Date date, String email, String phoneNumber, String twitterHandle, String instagramHandle, String teamSelected, String teamCountry, String location, String reference, int playerGroup, String mailStatus, boolean fixtureGenerated, boolean inTables, MultipartFile image) { PlayerId = playerId; this.firstName = firstName; this.lastName = lastName; this.fullName = fullName; this.alias = alias; this.date = date; this.email = email; this.phoneNumber = phoneNumber; this.twitterHandle = twitterHandle; this.instagramHandle = instagramHandle; this.teamSelected = teamSelected; this.teamCountry = teamCountry; this.location = location; this.reference = reference; this.playerGroup = playerGroup; this.mailStatus = mailStatus; this.fixtureGenerated = fixtureGenerated; this.inTables = inTables; this.image = image; }
@APIDeprecated( name = "/api/v1/pdf-generator/html", docLink = "https://github.com/hmcts/cmc-pdf-service#standard-api", expiryDate = "2018-02-08", note = "Please use `/pdfs` instead.") @ApiOperation("Returns a PDF file generated from provided HTML/Twig template and placeholder values") @PostMapping( value = "/html", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_PDF_VALUE ) public ResponseEntity<ByteArrayResource> generateFromHtml( @ApiParam("A HTML/Twig file. CSS should be embedded, images should be embedded using Data URI scheme") @RequestParam("template") MultipartFile template, @ApiParam("A JSON structure with values for placeholders used in template file") @RequestParam("placeholderValues") String placeholderValues ) { log.debug("Received a PDF generation request"); byte[] pdfDocument = htmlToPdf.convert(asBytes(template), asMap(placeholderValues)); log.debug("PDF generated"); return ResponseEntity .ok() .contentLength(pdfDocument.length) .body(new ByteArrayResource(pdfDocument)); }
/** * @api {patch} /credentials/:name Update * @apiParam {String} name Credential name to update * * @apiParamExample {multipart} RSA-Multipart-Body: * the same as create * * @apiGroup Credenital */ @PatchMapping(path = "/{name}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @WebSecurity(action = Actions.ADMIN_UPDATE) public Credential update(@PathVariable String name, @RequestParam(name = "detail") String detailJson, @RequestPart(name = "android-file", required = false) MultipartFile androidFile, @RequestPart(name = "p12-files", required = false) MultipartFile[] p12Files, @RequestPart(name = "pp-files", required = false) MultipartFile[] ppFiles) { // check name is existed if (!credentialService.existed(name)) { throw new IllegalParameterException("Credential name does not existed"); } CredentialDetail detail = jsonConverter.getGsonForReader().fromJson(detailJson, CredentialDetail.class); return createOrUpdate(name, detail, androidFile, p12Files, ppFiles); }
@ResponseBody @RequestMapping(value = "upload.do",method = RequestMethod.POST) public ServerResponse upload(HttpSession session,@RequestParam(value = "upload_file",required = false) MultipartFile file, HttpServletRequest request){ // TODO: 2017/8/4 这个required = false是指upload_file不是必须加的吗? User user = (User) session.getAttribute(Const.CURRENT_USER); if (user == null){ return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"请先登录"); } //判断这个用户是不是管理员 ServerResponse<String> checkRoleResult = iUserService.checkUserRole(user); if (checkRoleResult.isSuccess()){ //tomcat发布以后,会在webapp下创建一个upload文件夹,与index.jsp和WEB-INF同级 String path = request.getSession().getServletContext().getRealPath("upload"); String fileName = iFileService.upload(file, path); String url = PropertiesUtil.getProperty("ftp.server.http.prefix","http://img.happymmall.com/") +fileName; Map map = Maps.newHashMap(); map.put("uri",fileName); map.put("url",url); return ServerResponse.createBySuccess(map); } else { return ServerResponse.createByError("对不起,您没有管理员权限"); } }
@Test public void testCreateFromDocuments() throws Exception { List<MultipartFile> files = Stream.of( new MockMultipartFile("files", "filename.txt", "text/plain", "hello".getBytes(StandardCharsets.UTF_8)), new MockMultipartFile("files", "filename.txt", "text/plain", "hello2".getBytes(StandardCharsets.UTF_8))) .collect(Collectors.toList()); List<StoredDocument> storedDocuments = files.stream().map(f -> new StoredDocument()).collect(Collectors.toList()); when(this.auditedStoredDocumentOperationsService.createStoredDocuments(files)).thenReturn(storedDocuments); restActions .withAuthorizedUser("userId") .withAuthorizedService("divorce") .postDocuments("/documents", files, Classifications.PUBLIC, null) .andExpect(status().isOk()); }
private String saveUploadedFiles(List<MultipartFile> files) throws IOException { if (Files.notExists(Paths.get(UPLOADED_FOLDER))) { init(); } String randomPath = ""; for (MultipartFile file : files) { if (file.isEmpty()) { continue; //next pls } byte[] bytes = file.getBytes(); String fileName = file.getOriginalFilename(); String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); randomPath += generateRandomPath() + "." + suffix; Path path = Paths.get(UPLOADED_FOLDER + randomPath); Files.write(path, bytes); } return randomPath; }
@RequestMapping(value = "/upload", method = RequestMethod.POST) public @ResponseBody String fileUpload(MultipartFile file, ProjectFile pTarFile) { try { //decode pTarFile.setPFNotice(new String(pTarFile.getPFNotice().getBytes("iso-8859-1"), "UTF-8")); String realFileName = new String(file.getOriginalFilename().getBytes("iso-8859-1"), "UTF-8"); String suffix = realFileName.substring(realFileName.lastIndexOf(".") + 1); String savaFileStr = DateTime.now().toString() + "." + suffix; String PFId = projectService.addFiletoUWid(savaFileStr, pTarFile, file); pTarFile.setPFId(PFId); //动态生成更新字段 dynamicService.setProjectFileDynamic(pTarFile); return "ok"; } catch (IOException e) { e.printStackTrace(); } return "error:您没有在该阶段上传的权限"; }
@RequestMapping("/upload.do") public String upload(@RequestParam MultipartFile[] myfiles, HttpServletRequest request) throws IOException { for(MultipartFile file : myfiles){ //此处MultipartFile[]表明是多文件,如果是单文件MultipartFile就行了 if(file.isEmpty()){ System.out.println("文件未上传!"); } else{ //得到上传的文件名 String fileName = file.getOriginalFilename(); //得到服务器项目发布运行所在地址 String path1 = request.getSession().getServletContext().getRealPath("file")+ File.separator; // 此处未使用UUID来生成唯一标识,用日期做为标识 String path2 = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ fileName; request.getSession().setAttribute("document",path2); String path = path1+path2; //查看文件上传路径,方便查找 System.out.println(path); //把文件上传至path的路径 File localFile = new File(path); file.transferTo(localFile); } } return "redirect:/student/uploadDocument"; }
/** * The storing method should be able to adapt to all types of storing: requests, templates and responses from institutions * * @param files a list files that will be uploaded */ @Override public boolean store(List<MultipartFile> files, Path path) { try { for (MultipartFile file : files) { if (file.isEmpty()) { continue; // give me another one } byte[] bytes = file.getBytes(); Files.write(path, bytes); } } catch (IOException ioe) { logger.error(ioe.getStackTrace()); return false; } return true; }
/** * 判断上传文件是否为图片 * * @param MultipartFile * @return NULL为TRUE */ public static boolean isPhoto(MultipartFile file) { if (file == null) { return false; } String originalFilename = file.getOriginalFilename(); if (originalFilename == null || originalFilename.length() == 0) { return false; } // 获取文件后缀 String fileSuffix = UploadUtil.getFileSuffix(originalFilename); if (fileSuffix == null || fileSuffix.length() == 0) { // 通过Mime类型获取文件类型 fileSuffix = ContentTypeUtil.getFileTypeByMimeType(file.getContentType()); } if(fileSuffix==null || fileSuffix.equals("")) { return false; } if(PhotoSuffix.indexOf(fileSuffix.toLowerCase()) != -1){ return true; } return false; }
/** * 上传发布流程定义. */ @RequestMapping("console-process-upload") public String processUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) throws Exception { String tenantId = tenantHolder.getTenantId(); String fileName = file.getOriginalFilename(); Deployment deployment = processEngine.getRepositoryService() .createDeployment() .addInputStream(fileName, file.getInputStream()) .tenantId(tenantId).deploy(); List<ProcessDefinition> processDefinitions = processEngine .getRepositoryService().createProcessDefinitionQuery() .deploymentId(deployment.getId()).list(); for (ProcessDefinition processDefinition : processDefinitions) { processEngine.getManagementService().executeCommand( new SyncProcessCmd(processDefinition.getId())); } return "redirect:/bpm/console-listProcessDefinitions.do"; }
/** * 上传文件 */ @RequestMapping("/upload") @RequiresPermissions("sys:oss:all") public R upload(@RequestParam("file") MultipartFile file) throws Exception { if (file.isEmpty()) { throw new RRException("上传文件不能为空"); } //上传文件 String url = OSSFactory.build().upload(file.getBytes()); //保存文件信息 SysOssEntity ossEntity = new SysOssEntity(); ossEntity.setUrl(url); ossEntity.setCreateDate(new Date()); sysOssService.save(ossEntity); return R.ok().put("url", url); }
public ResultActions postDocument(String urlTemplate, MultipartFile file) { return translateException(() -> mvc.perform( MockMvcRequestBuilders.fileUpload(urlTemplate).file((MockMultipartFile)file) .headers(httpHeaders) )); }
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST) public View uploadFile(@RequestParam("file") MultipartFile file) { try { InputStream input = file.getInputStream(); this.messageManagementService.importFromExcel(input); } catch (Exception e) { LOG.error("error on uploading messages", e); return new RedirectView("../files.html?uploadSuccess=no&message=" + e.getMessage().toString()); } return new RedirectView("../files.html?uploadSuccess=yes"); }
/** * Transfers content of the given {@code Multipart} entity to a temporary file. * * @param multipart {@code Multipart} used to handle file uploads * @return {@code File} represents a reference on a file that has been created * from the given {@code Multipart} * @throws IOException */ protected File transferToTempFile(final MultipartFile multipart) throws IOException { Assert.notNull(multipart); final File tmp = File.createTempFile(UUID.randomUUID().toString(), multipart.getOriginalFilename(), fileManager.getTempDir()); multipart.transferTo(tmp); FileUtils.forceDeleteOnExit(tmp); return tmp; }
/** * Upload image file to Azure blob and save its relative path to database. * * @param file image file * @param id movie id * @return updated movie detail page */ @RequestMapping(value = "/upload", method = RequestMethod.POST) public String updateMovieImage(@RequestParam("file") MultipartFile file, @RequestParam("id") Long id) { logger.debug(file.getOriginalFilename()); String newName = id + "." + FilenameUtils.getExtension(file.getOriginalFilename()); String imageUri = this.azureStorageUploader.uploadToAzureStorage(applicationContext, file, newName.toLowerCase()); if (imageUri != null) { Timestamp timestamp = new Timestamp(Calendar.getInstance().getTime().getTime()); String timestampQuery = "?timestamp=" + timestamp.toString(); Movie movie = new Movie(); movie.setImageUri(imageUri.toLowerCase() + timestampQuery); movieRepository.patchMovie(Long.toString(id), movie); } return "redirect:/movies/" + id; }
@PostMapping(path = "/calculate-range-statistics") public @ResponseBody Callable<ResponseEntity<byte[]>> calculateRangeStatistics(@RequestParam("files") List<MultipartFile> files) { LOGGER.info("calculateRangeStatistics({})", files); return () -> ResponseEntity.ok(). contentType(MediaType.APPLICATION_OCTET_STREAM). header("Content-Disposition", "attachment; filename=\"range-statistics.zip\""). body(ZipHelper.zipRangeStatistics( countService.calculateRangeStatistics( files.stream().map(file -> { try { return IOUtils.toString(file.getBytes(), Charset.defaultCharset().name()); } catch (IOException e) { throw new CounterApiException("error.read.file", file.getName()).withCause(e); } }).collect(Collectors.toList())))); }
@RequestMapping("upload.do") @ResponseBody public String upload(@RequestParam("file") MultipartFile uploadfile, HttpSession session){ String filename= uploadfile.getOriginalFilename(); String leftPath= session.getServletContext().getRealPath("file"); String message=null; File file=new File(leftPath,filename); if (!file.exists()) { file.mkdirs(); } try { uploadfile.transferTo(file); String path=file.getAbsolutePath(); FileUpLoad.readExcel(path); if(file.isFile()){ file.delete(); } message="1"; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); log.error("�ļ��������"); message="0"; } return message; }
private IGraphVersionMetadataDTO importGraph(String graphName, String version, boolean overrideIfExists, MultipartFile file) throws GraphAlreadyExistException, GraphImportException, IOException { IWayGraphVersionMetadata metadata = this.graphApiService.importGraph(graphName, version, overrideIfExists, file); log.info("Import finished"); return this.adapter.adapt(metadata); }
public void updateLogo(MultipartHttpServletRequest multipartReq, App app) throws IOException, MalformedURLException, URISyntaxException { int id = app.getId(); // logo. 浏览器上传用户本地文件 或 下载远端服务器 图片. String logoUrlBak = multipartReq.getParameter("oldLogoUrl");// app.getLogoUrl(); boolean needToDeleteLogoUrlBak = false; String remoteLogoUrl = multipartReq.getParameter("remoteLogoUrl"); MultipartFile file = multipartReq.getFile("logoFile"); String logoSubPath = null; if (file != null && !file.isEmpty()) { logoSubPath = attachmentService.saveFile(id, file); } else if (StringUtils.isNotBlank(remoteLogoUrl)) { // 拉取图片. logoSubPath = attachmentService.saveFile(id, remoteLogoUrl); } if (StringUtils.isNotBlank(logoSubPath)) { String logoUrl = PathUtils.concate(appConfig.getDestUploadBaseurl(), logoSubPath); app.setLogoUrl(logoUrl); saveOrUpdate(app); needToDeleteLogoUrlBak = true; } if (StringUtils.isNotBlank(logoUrlBak) && needToDeleteLogoUrlBak) { attachmentService.deleteFile(logoUrlBak); } appHistory4IndexDao.saveOrUpdate(app.getId()); }
@RequestMapping(value = ENDPOINT_ROINT + "/{name}", method = RequestMethod.POST) @PreAuthorize(BotApiApplication.HAS_AUTH_ROLE_ORCHESTRATOR) public @ResponseBody Long uploadCamera(@RequestParam("file") MultipartFile file, @PathVariable("name") final String name) throws IOException { BotCamera botCam = new BotCamera(file.getBytes(), new Date()); PlayerBot playerBot = playerBotRepository.findByName(name); botCam.setPlayerBot(playerBot); botCam = botCameraRepository.save(botCam); return botCam.getId(); }
@RequestMapping(method = RequestMethod.POST, value = "/update.do") public void update(int id, String title, Double marketPrice, Double shopPrice, String desc, int csid, int isHot, MultipartFile image, HttpServletRequest request, HttpServletResponse response) throws Exception { Product product = productService.findById(id); product.setTitle(title); product.setMarketPrice(marketPrice); product.setShopPrice(shopPrice); product.setDesc(desc); product.setIsHot(isHot); product.setCsid(csid); product.setPdate(new Date()); String imgUrl = FileUtil.saveFile(image); if (StringUtils.isNotBlank(imgUrl)) { product.setImage(imgUrl); } boolean flag = false; try { productService.update(product); flag = true; } catch (Exception e) { throw new Exception(e); } if (!flag) { request.setAttribute("message", "更新失败!"); } response.sendRedirect("toList.html"); }
public String store(MultipartFile file) { try { if (file.isEmpty()) { throw new SIIStemTechnicalException("Failed to store empty file " + file.getOriginalFilename()); } Path pathToSave = this.imagesPath.resolve(UUID.randomUUID().toString() + ".original" + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'))); Files.copy(file.getInputStream(), pathToSave); return pathToSave.toString(); } catch (IOException e) { throw new SIIStemTechnicalException("Failed to store file " + file.getOriginalFilename(), e); } }
protected FResult<String> transferSpringRequestStreamToHD(UploadRequest uploadRequest, String saveTempFileDirectory, HttpServletRequest request) { MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; Map<String, MultipartFile> fileMaps = multiRequest.getFileMap(); if (fileMaps != null && fileMaps.size() == 1) { for (Entry<String, MultipartFile> fileEntry : fileMaps.entrySet()) { if (fileEntry != null && !fileEntry.getValue().isEmpty()) { // 得到本次上传文件 MultipartFile multiFile = fileEntry.getValue(); String originalFilename = multiFile.getOriginalFilename(); uploadRequest.setOriginalExtName(FilenameUtils.getExtension(originalFilename)); String fileName = UUID.randomUUID().toString() + "." + uploadRequest.getOriginalExtName(); if (StringUtils.isBlank(uploadRequest.getOriginalFilename())) { uploadRequest.setOriginalFilename(fileName); } else { uploadRequest.setOriginalFilename(originalFilename); } String fileFullPath = saveTempFileDirectory + File.separator + fileName; log.debug("file temp path : " + fileFullPath); // 构造临时文件 File uploadTempFile = new File(fileFullPath); try { // 临时文件持久化到硬盘 multiFile.transferTo(uploadTempFile); uploadRequest.setTemporaryFilePath(fileFullPath); uploadRequest.setTemporaryFileSize(uploadTempFile.length()); } catch (IllegalStateException | IOException e) { log.error("上传文件持久化到服务器失败,计划持久化文件 ", e); return FResult.newFailure(HttpResponseCode.SERVER_IO_ERROR, "上传文件持久化到服务器失败"); } } } return FResult.newSuccess("上传成功"); } else { return FResult.newFailure(HttpResponseCode.CLIENT_PARAM_INVALID, "一次请求仅支持上传一个文件"); } }
private void checkImageFile(MultipartFile file) { String mimeType = file.getContentType(); String type = mimeType.split("/")[0]; if (!type.equalsIgnoreCase("image")) { throw new IllegalArgumentException(file.getOriginalFilename() + " is not image file."); } }
private List<PhotoLocationSightPair> loadSightPairs(Path exercisePath, PhotoLocationExercise exercise, Boolean dryRun) throws BuenOjoDataSetException { try { Path sightPairsFilePath = exercisePath.resolve(sightFilename); MultipartFile file = BuenOjoFileUtils.multipartFile(sightPairsFilePath); return sightPairFactory.setSightPairs(exercise, file); } catch (IOException | BuenOjoCSVParserException e) { throw new BuenOjoDataSetException(e); } }
@PostMapping("/xm-entities/{idOrKey}/links/targets") @Timed public ResponseEntity<Link> saveLinkTarget(@PathVariable String idOrKey, @RequestPart("link") Link link, @RequestPart(value = "file", required = false) MultipartFile file) { log.debug("REST request to create target for entity {}", idOrKey); Link result = xmEntityService.saveLinkTarget(IdOrKey.of(idOrKey), link, file); return ResponseEntity.ok().body(result); }
/** * Converts the array of MultipartFiles into a 2-dimensional byte array containing content from * each MultipartFile. The 2-dimensional byte array format is used by Gfsh and the GemFire Manager * to transmit file data. * <p/> * * @param files an array of Spring MultipartFile objects to convert into the 2-dimensional byte * array format. * @return a 2-dimensional byte array containing the content of each MultipartFile. * @throws IOException if an I/O error occurs reading the contents of a MultipartFile. * @see #convert(org.springframework.core.io.Resource...) * @see org.springframework.web.multipart.MultipartFile */ public static byte[][] convert(final MultipartFile... files) throws IOException { if (files != null) { final List<Resource> resources = new ArrayList<Resource>(files.length); for (final MultipartFile file : files) { resources.add(new MultipartFileResourceAdapter(file)); } return convert(resources.toArray(new Resource[resources.size()])); } return new byte[0][]; }
@ApiOperation(value = "Uploads a file.", notes = "", response = Void.class, authorizations = { @Authorization(value = "Bearer") }, tags={ "admin", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Picture set", response = Void.class), @ApiResponse(code = 500, message = "An unexpected error occured.", response = Void.class) }) @RequestMapping(value = "/users/{id}/picture", produces = { "application/json" }, consumes = { "multipart/form-data" }, method = RequestMethod.POST) @CrossOrigin ResponseEntity<Void> usersIdPicturePost(@ApiParam(value = "user id",required=true ) @PathVariable("id") Integer id, @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file)throws ApiException;
@Test public void testUploadDocumentsMalformedFail() { List<MultipartFile> files = Stream.of( new MockMultipartFile("files", "filename.txt", "tex", "hello".getBytes(StandardCharsets.UTF_8)) ).collect(Collectors.toList()); boolean b = fileWhiteListValidator.isValid(files, null); assertFalse(b); }
public static String copyMultipartFileToFile(String baseDir, MultipartFile multipartFile, String spaceName) throws Exception { String targetFileName = generateTargetFileName(multipartFile .getOriginalFilename()); return copyMultipartFileToFile(baseDir, multipartFile, spaceName, targetFileName); }
@RequestMapping(value = "/upload", method = RequestMethod.POST) public void upload(MultipartFile file, HttpServletResponse response) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(file.getInputStream(), out); Swagger swagger = new SwaggerParser() .parse(out.toString("utf-8")); out.close(); String content = objectMapper.writeValueAsString(swagger); documentService.save(new Document() .setContent(content) .setTitle(file.getOriginalFilename())); applicationEventPublisher.publishEvent(new InstanceRegisteredEvent<>(SwaggerDocDiscovery.class, swagger)); response.sendRedirect("/#/document.html"); }
public File convert(MultipartFile file) throws IOException { File convFile = new File(file.getOriginalFilename()); convFile.createNewFile(); FileOutputStream fos = new FileOutputStream(convFile); fos.write(file.getBytes()); fos.close(); return convFile; }
@ApiOperation(value = "Uploads a file.", notes = "", response = Void.class, authorizations = { @Authorization(value = "Bearer") }, tags={ }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Picture set", response = Void.class), @ApiResponse(code = 500, message = "An unexpected error occured.", response = Void.class) }) @RequestMapping(value = "/settings/picture", produces = { "application/json" }, consumes = { "multipart/form-data" }, method = RequestMethod.POST) @CrossOrigin ResponseEntity<Void> settingsPicturePost(@ApiParam(value = "file detail") @RequestPart("file") MultipartFile upfile, @ApiParam(value = "Description of file contents." ) @RequestPart(value="userid", required=false) Integer userid) throws ApiException;
@Override public void sendTemplateMailWithAttachment(final String fromAddress, final String toAddress, final String ccAddress, final String subject, final Map<String, Object> modelForMailContent, final String templateName, final boolean isTemplateHtml, final List<MultipartFile> attachFiles) throws Exception { if (StringUtils.isNotBlank(ccAddress)) { sendVelocityTemplateMailWithAttachment(fromAddress, Arrays.asList(toAddress), Arrays.asList(ccAddress), subject, modelForMailContent, templateName, isTemplateHtml, attachFiles); } else { sendVelocityTemplateMailWithAttachment(fromAddress, Arrays.asList(toAddress), new ArrayList<String>(), subject, modelForMailContent, templateName, isTemplateHtml, attachFiles); } }
/** * Supplier for file input * * @param file the attachment * @return a supplier that wraps the attachment's input stream retrieval */ Supplier<InputStream> inputStreamSupplier(MultipartFile file) { return () -> { try { return file.getInputStream(); } catch (IOException ex) { throw new UncheckedIOException(ex); } }; }
@Override public String saveMarketAppFile(int id, MultipartFile file) throws IllegalStateException, IOException { if (file == null) { throw new NullPointerException(); } String filename = newDateTimeString(); StringBuilder path = new StringBuilder(24).append(id).append("/").append(filename); String extension = getExtensionFromContentType(file.getContentType()); path.append(".").append(extension); File dest = new File(PathUtils.concate(appConfig.getDestBigGameUploadDir(), path.toString())); PathUtils.makeSureDir(dest.getParentFile()); file.transferTo(dest); return path.toString(); }