Java Code Examples for org.springframework.http.MediaType#MULTIPART_FORM_DATA_VALUE

The following examples show how to use org.springframework.http.MediaType#MULTIPART_FORM_DATA_VALUE . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UploadController.java    From spring-boot-demo with MIT License 8 votes vote down vote up
@PostMapping(value = "/local", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Dict local(@RequestParam("file") MultipartFile file) {
	if (file.isEmpty()) {
		return Dict.create().set("code", 400).set("message", "文件内容为空");
	}
	String fileName = file.getOriginalFilename();
	String rawFileName = StrUtil.subBefore(fileName, ".", true);
	String fileType = StrUtil.subAfter(fileName, ".", true);
	String localFilePath = StrUtil.appendIfMissing(fileTempPath, "/") + rawFileName + "-" + DateUtil.current(false) + "." + fileType;
	try {
		file.transferTo(new File(localFilePath));
	} catch (IOException e) {
		log.error("【文件上传至本地】失败,绝对路径:{}", localFilePath);
		return Dict.create().set("code", 500).set("message", "文件上传失败");
	}

	log.info("【文件上传至本地】绝对路径:{}", localFilePath);
	return Dict.create().set("code", 200).set("message", "上传成功").set("data", Dict.create().set("fileName", fileName).set("filePath", localFilePath));
}
 
Example 2
Source File: HttpBinCompatibleController.java    From spring-cloud-gateway with Apache License 2.0 7 votes vote down vote up
@RequestMapping(value = "/post", consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
		produces = MediaType.APPLICATION_JSON_VALUE)
public Mono<Map<String, Object>> postFormData(
		@RequestBody Mono<MultiValueMap<String, Part>> parts) {
	// StringDecoder decoder = StringDecoder.allMimeTypes(true);
	return parts.flux().flatMap(map -> Flux.fromIterable(map.values()))
			.flatMap(Flux::fromIterable).filter(part -> part instanceof FilePart)
			.reduce(new HashMap<String, Object>(), (files, part) -> {
				MediaType contentType = part.headers().getContentType();
				long contentLength = part.headers().getContentLength();
				// TODO: get part data
				files.put(part.name(),
						"data:" + contentType + ";base64," + contentLength);
				return files;
			}).map(files -> Collections.singletonMap("files", files));
}
 
Example 3
Source File: HelloController.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
@PostMapping(value = "/files", produces = { MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
@Operation(summary = "files")
public Flux<Void> handleFileUpload(
		@RequestPart("files") @Parameter(description = "files",
				content = @Content(mediaType = MediaType.APPLICATION_OCTET_STREAM_VALUE))
				Flux<FilePart> filePartFux) throws IOException {
	File tmp = File.createTempFile("tmp", "");
	return filePartFux.flatMap(filePart -> {
		Path path = Paths.get(tmp.toString() + filePart.filename());
		System.out.println(path);
		return filePart.transferTo(path);
	});
}
 
Example 4
Source File: WorkflowProcessDefinitionController.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
@PostMapping(value = "/process/definitions/import", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
public CommonResponseDto importProcessDefinition(@RequestParam("uploadFile") MultipartFile file,
        HttpServletRequest request) {
    if (file == null || file.getSize() <= 0) {
        log.error("invalid file content uploaded");
        throw new WecubeCoreException("Invalid file content uploaded.");
    }

    if (log.isInfoEnabled()) {
        log.info("About to import process definition,filename={},size={}", file.getOriginalFilename(),
                file.getSize());
    }

    try {
        String filedata = IOUtils.toString(file.getInputStream(), Charset.forName("utf-8"));
        String jsonData = new String(StringUtilsEx.decodeBase64(filedata), Charset.forName("utf-8"));
        ProcDefInfoExportImportDto importDto = convertImportData(jsonData);

        String token = request.getHeader("Authorization");

        ProcDefInfoExportImportDto result = procDefService.importProcessDefinition(importDto, token);
        return CommonResponseDto.okayWithData(result);
    } catch (IOException e) {
        log.error("errors while reading upload file", e);
        throw new WecubeCoreException("Failed to import process definition.");
    }

}
 
Example 5
Source File: RuleController.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
    * API to create new rule
    *
    * @author Nidhish
    * @param fileToUpload - valid executable rule jar file
    * @param createRuleDetails - details for creating new rule
    * @return Success or Failure response
    */
@ApiOperation(httpMethod = "POST", value = "API to create new rule", response = Response.class, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@RequestMapping(path = "/create", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<Object> createRule(@AuthenticationPrincipal Principal user,
		@ApiParam(value = "provide valid rule details", required = false) @RequestParam(defaultValue="", value = "file", required = false) MultipartFile fileToUpload, CreateUpdateRuleDetails createRuleDetails) {
	try {
		return ResponseUtils.buildSucessResponse(ruleService.createRule(fileToUpload, createRuleDetails, user.getName()));
	} catch (Exception exception) {
		log.error(UNEXPECTED_ERROR_OCCURRED, exception);
		return ResponseUtils.buildFailureResponse(new Exception(UNEXPECTED_ERROR_OCCURRED), exception.getMessage());
	}
}
 
Example 6
Source File: EmailController.java    From open-cloud with MIT License 5 votes vote down vote up
/**
 * 发送模板邮件
 *
 * @param to          接收人 多个用;号隔开
 * @param cc          抄送人 多个用;号隔开
 * @param subject     主题
 * @param tplCode     内容
 * @param tplCode     模板编号
 * @param tplParams   模板参数 json字符串
 * @param attachments 附件
 * @return
 */
@Override
@ApiOperation(value = "发送模板邮件", notes = "发送模板邮件")
@ApiImplicitParams({
        @ApiImplicitParam(name = "to", required = true, value = "接收人 多个用;号隔开", paramType = "form"),
        @ApiImplicitParam(name = "cc", required = false, value = "抄送人 多个用;号隔开", paramType = "form"),
        @ApiImplicitParam(name = "subject", required = true, value = "主题", paramType = "form"),
        @ApiImplicitParam(name = "tplCode", required = true, value = "模板编号", paramType = "form"),
        @ApiImplicitParam(name = "tplParams", required = true, value = "模板参数 json字符串", paramType = "form"),
        @ApiImplicitParam(name = "attachments", required = false, value = "附件:最大不超过10M", dataType = "file", paramType = "form", allowMultiple = true),
})
@PostMapping(value = "/email/send/tpl", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResultBody sendByTpl(
        @RequestParam(value = "to") String to,
        @RequestParam(value = "cc", required = false) String cc,
        @RequestParam(value = "subject") String subject,
        @RequestParam(value = "tplCode") String tplCode,
        @RequestParam(value = "tplParams") String tplParams,
        @RequestPart(value = "attachments", required = false) MultipartFile[] attachments
) {
    EmailTplMessage message = new EmailTplMessage();
    message.setTo(StringUtils.delimitedListToStringArray(to, ";"));
    message.setCc(StringUtils.delimitedListToStringArray(cc, ";"));
    message.setSubject(subject);
    message.setAttachments(MultipartUtil.getMultipartFilePaths(attachments));
    message.setTplCode(tplCode);
    message.setTplParams(JSONObject.parseObject(tplParams));
    this.dispatcher.dispatch(message);
    return ResultBody.ok();
}
 
Example 7
Source File: ValidFeignClientTests.java    From spring-cloud-openfeign with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.POST, path = "/multipartFilenames",
		consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
		produces = MediaType.TEXT_PLAIN_VALUE)
String multipartFilenames(HttpServletRequest request) throws Exception {
	return request.getParts().stream().map(Part::getSubmittedFileName)
			.collect(Collectors.joining(","));
}
 
Example 8
Source File: PluginConfigController.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
@PostMapping(value = "/plugins/packages/import/{plugin-package-id:.+}", consumes = {
        MediaType.MULTIPART_FORM_DATA_VALUE })
public CommonResponseDto importPluginPackageRegistries(
        @PathVariable(value = "plugin-package-id") String pluginPackageId,
        @RequestParam(value = "xml-file") MultipartFile xmlFile) {

    if (xmlFile == null || xmlFile.getSize() <= 0) {
        log.error("invalid file content uploaded");
        throw new WecubeCoreException("Invalid file content uploaded.");
    }

    if (log.isInfoEnabled()) {
        log.info("About to import plugin package registries,filename={},size={}", xmlFile.getOriginalFilename(),
                xmlFile.getSize());
    }

    try {
        String xmlData = IOUtils.toString(xmlFile.getInputStream(), Charset.forName("UTF-8"));

        pluginConfigService.importPluginRegistersForOnePackage(pluginPackageId, xmlData);
        return CommonResponseDto.okay();
    } catch (IOException e) {
        log.error("errors while reading upload file", e);
        throw new WecubeCoreException("Failed to import plugin package registries.");
    }

}
 
Example 9
Source File: TvSeriesController.java    From tutorial with MIT License 5 votes vote down vote up
/**
 * 给电视剧添加剧照。
 * 这是一个文件上传的例子(具体上传处理代码没有写)
 * @param id
 * @param imgFile
 * @throws Exception
 */
@PostMapping(value="/{id}/photos", consumes=MediaType.MULTIPART_FORM_DATA_VALUE)
public void addPhoto(@PathVariable int id, @RequestParam("photo") MultipartFile imgFile) throws Exception{
    if(log.isTraceEnabled()) {
        log.trace("接受到文件 " + id + "收到文件:" + imgFile.getOriginalFilename());
    }
    //保存文件
    FileOutputStream fos = new FileOutputStream("target/" + imgFile.getOriginalFilename());
    IOUtils.copy(imgFile.getInputStream(), fos);
    fos.close();
}
 
Example 10
Source File: MockDefinitionImportExportController.java    From smockin with Apache License 2.0 5 votes vote down vote up
@RequestMapping(path="/mock/import", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public @ResponseBody ResponseEntity<SimpleMessageResponseDTO> importMocks(@RequestHeader(value = GeneralUtils.OAUTH_HEADER_NAME, required = false) final String bearerToken,
                                                                          @RequestHeader(value = GeneralUtils.KEEP_EXISTING_HEADER_NAME) final boolean keepExisting,
                                                                          @RequestParam("file") final MultipartFile file)
                                                        throws ValidationException, MockImportException, RecordNotFoundException {

    final String token = GeneralUtils.extractOAuthToken(bearerToken);

    final MockImportConfigDTO configDTO = (keepExisting)
            ? new MockImportConfigDTO(MockImportKeepStrategyEnum.RENAME_NEW )
            : new MockImportConfigDTO();

    return ResponseEntity.ok(new SimpleMessageResponseDTO(mockDefinitionImportExportService
            .importFile(file, configDTO, token)));
}
 
Example 11
Source File: ValidFeignClientTests.java    From spring-cloud-openfeign with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.POST, path = "/multipart",
		consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
		produces = MediaType.TEXT_PLAIN_VALUE)
String multipart(@RequestPart("hello") String hello,
		@RequestPart("world") String world,
		@RequestPart("file") MultipartFile file) {
	return hello + world + file.getOriginalFilename();
}
 
Example 12
Source File: ValidFeignClientTests.java    From spring-cloud-openfeign with Apache License 2.0 4 votes vote down vote up
@RequestMapping(method = RequestMethod.POST, path = "/multipartNames",
		consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
		produces = MediaType.TEXT_PLAIN_VALUE)
String requestBodyListOfMultipartFiles(@RequestBody List<MultipartFile> files);
 
Example 13
Source File: FileUploadController.java    From springfox-demos with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "/upload", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE }, method = RequestMethod.POST)
public ResponseEntity<Void> uploadFile(@RequestPart String description, @RequestPart MultipartFile file) {
    //yaay!
    return ResponseEntity.ok(null);
}
 
Example 14
Source File: ValidFeignClientTests.java    From spring-cloud-openfeign with Apache License 2.0 4 votes vote down vote up
@RequestMapping(method = RequestMethod.POST, path = "/multipartPojosFiles",
		consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
		produces = MediaType.TEXT_PLAIN_VALUE)
String requestPartListOfPojosAndListOfMultipartFiles(
		@RequestPart("pojos") List<Hello> pojos,
		@RequestPart("files") List<MultipartFile> files);
 
Example 15
Source File: MultipartController.java    From spring-reactive-sample with GNU General Public License v3.0 4 votes vote down vote up
@PostMapping(value = "", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
Mono<String> requestBodyFlux(@RequestBody Flux<Part> parts) {
    return partFluxDescription(parts);
}
 
Example 16
Source File: DataVirtualizationService.java    From syndesis with Apache License 2.0 4 votes vote down vote up
/**
 * Export the virtualization to a zip file
 */
@RequestMapping(value = {VIRTUALIZATION_PLACEHOLDER + StringConstants.FS + "export",
        VIRTUALIZATION_PLACEHOLDER + StringConstants.FS + "export" + StringConstants.FS + REVISION_PLACEHOLDER}, method = RequestMethod.GET, produces = {
        MediaType.MULTIPART_FORM_DATA_VALUE })
@ApiOperation(value = "Export virtualization by name.  Without a revision number, the current working state is exported.", response = RestDataVirtualization.class)
@ApiResponses(value = { @ApiResponse(code = 404, message = "No virtualization could be found with name"),
        @ApiResponse(code = 406, message = "Only JSON is returned by this operation"),
        @ApiResponse(code = 403, message = AN_ERROR_HAS_OCCURRED) })
public ResponseEntity<StreamingResponseBody> exportDataVirtualization(
        @ApiParam(value = "name of the virtualization",
        required = true) final @PathVariable(VIRTUALIZATION) String virtualization,
        @ApiParam(value = "revision number",
        required = false) final @PathVariable(required = false, name = REVISION) Long revision)
        {

    StreamingResponseBody result = repositoryManager.runInTransaction(true, () -> {
        DataVirtualization dv = getWorkspaceManager().findDataVirtualization(virtualization);

        if (dv == null) {
            throw notFound(virtualization);
        }

        if (revision != null) {
            Edition e = repositoryManager.findEdition(virtualization, revision);
            if (e == null) {
                throw notFound(String.valueOf(revision));
            }

            byte[] bytes = repositoryManager.findEditionExport(e);
            Assertion.isNotNull(bytes);

            return out -> {
                out.write(bytes);
            };
        }

        return createExportStream(dv, null, null);
    });


    MultiValueMap<String, String> headers = new HttpHeaders();
    headers.add("Content-Disposition", "attachment; filename=\""+virtualization+(revision!=null?"-"+revision:"")+"-export.zip\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
    return new ResponseEntity<StreamingResponseBody>(result, headers, HttpStatus.OK);
}
 
Example 17
Source File: ValidFeignClientTests.java    From spring-cloud-openfeign with Apache License 2.0 4 votes vote down vote up
@RequestMapping(method = RequestMethod.POST, path = "/singlePojoPart",
		consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
		produces = MediaType.TEXT_PLAIN_VALUE)
String singlePojoPart(@RequestPart("hello") Hello hello) {
	return hello.getMessage();
}
 
Example 18
Source File: FileService.java    From NetworkDisk_Storage with GNU General Public License v2.0 4 votes vote down vote up
@RequestMapping(value = "upload", method = RequestMethod.POST,consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
RestAPIResult<String> upload(@RequestPart MultipartFile file) throws IOException;
 
Example 19
Source File: TransformationService.java    From data-prep with Apache License 2.0 3 votes vote down vote up
/**
 * This operation allow client to create a diff between 2 list of actions starting from the same data. For example,
 * sending:
 * <ul>
 * <li>{a1, a2} as old actions</li>
 * <li>{a1, a2, a3} as new actions</li>
 * </ul>
 * ... will highlight changes done by a3.
 * <p>
 * To prevent the actions to exceed URL length limit, everything is shipped within via the multipart request body.
 *
 * @param previewParameters The preview parameters, encoded in json within the request body.
 * @param output Where to write the response.
 */
//@formatter:off
@RequestMapping(value = "/transform/preview", method = POST, produces = APPLICATION_JSON_VALUE)
@ApiOperation(value = "Preview the transformation on input data", notes = "This operation returns the input data diff between the old and the new transformation actions", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@VolumeMetered
public void transformPreview(@ApiParam(name = "body", value = "Preview parameters.") @RequestBody final PreviewParameters previewParameters,
                             final OutputStream output) {
    //@formatter:on
    if (shouldApplyDiffToSampleSource(previewParameters)) {
        executeDiffOnSample(previewParameters, output);
    } else {
        executeDiffOnDataset(previewParameters, output);
    }
}
 
Example 20
Source File: FileUploadFeignService.java    From fw-spring-cloud with Apache License 2.0 2 votes vote down vote up
/***
 * 1.produces,consumes必填
 * 2.注意区分@RequestPart和RequestParam,不要将
 * : @RequestPart(value = "file") 写成@RequestParam(value = "file")
 */
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
String uploadFile(@RequestPart(value = "file") MultipartFile file);