use of org.springframework.web.multipart.MultipartHttpServletRequest in project Gemma by PavlidisLab.
the class FileUploadUtil method copyUploadedFile.
public static File copyUploadedFile(HttpServletRequest request, String key) throws IOException {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile(key);
if (file == null) {
throw new IllegalArgumentException("File with key " + key + " was not in the request");
}
return copyUploadedFile(file, request);
}
use of org.springframework.web.multipart.MultipartHttpServletRequest in project com.revolsys.open by revolsys.
the class WebMethodHandler method body.
@SuppressWarnings({ "unchecked", "rawtypes" })
public static WebParameterHandler body(final WebAnnotationMethodHandlerAdapter adapter, final Parameter parameter, final Annotation annotation) {
final boolean required = ((RequestBody) annotation).required();
final String parameterName = parameter.getName();
final Class parameterClass = parameter.getType();
final DataType dataType = DataTypes.getDataType(parameterClass);
return //
WebParameterHandler.function(//
parameterName, (request, response) -> {
try {
final HttpInputMessage inputMessage = new ServletServerHttpRequest(request);
MediaType contentType = MediaTypeUtil.getContentType(request);
if (contentType == null) {
contentType = MediaType.APPLICATION_FORM_URLENCODED;
}
if (!MediaType.APPLICATION_FORM_URLENCODED.includes(contentType) && !MediaType.MULTIPART_FORM_DATA.includes(contentType)) {
contentType = MediaTypeUtil.getRequestMediaType(request, adapter.mediaTypes, adapter.mediaTypeOrder, adapter.urlPathHelper, adapter.parameterName, adapter.defaultMediaType, "");
}
final HttpHeaders headers = inputMessage.getHeaders();
if (contentType == null) {
final StringBuilder builder = new StringBuilder(ClassUtils.getShortName(parameterClass));
final String paramName = parameterName;
if (paramName != null) {
builder.append(' ');
builder.append(paramName);
}
throw new HttpMediaTypeNotSupportedException("Cannot extract @RequestBody parameter (" + builder.toString() + "): no Content-Type found");
} else {
HttpServletUtils.setContentTypeWithCharset(headers, contentType);
}
final List<MediaType> allSupportedMediaTypes = new ArrayList<>();
if (adapter.messageConverters != null) {
for (final HttpMessageConverter<?> messageConverter : adapter.messageConverters) {
allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes());
if (messageConverter.canRead(parameterClass, contentType)) {
return messageConverter.read(parameterClass, inputMessage);
}
}
String body = null;
if (MediaType.APPLICATION_FORM_URLENCODED.includes(contentType)) {
Charset charset = contentType.getCharSet();
if (charset == null) {
charset = StandardCharsets.UTF_8;
}
final String urlBody = FileCopyUtils.copyToString(new InputStreamReader(inputMessage.getBody(), charset));
final String[] pairs = StringUtils.tokenizeToStringArray(urlBody, "&");
final MultiValueMap<String, String> values = new LinkedMultiValueMap<>(pairs.length);
for (final String pair : pairs) {
final int idx = pair.indexOf('=');
if (idx == -1) {
values.add(URLDecoder.decode(pair, charset.name()), null);
} else {
final String name = URLDecoder.decode(pair.substring(0, idx), charset.name());
final String value = URLDecoder.decode(pair.substring(idx + 1), charset.name());
values.add(name, value);
}
}
body = values.getFirst("body");
} else if (request instanceof MultipartHttpServletRequest) {
final MultipartHttpServletRequest multiPartRequest = (MultipartHttpServletRequest) request;
final MultipartFile bodyFile = multiPartRequest.getFile("body");
contentType = MediaTypeUtil.getRequestMediaType(request, adapter.mediaTypes, adapter.mediaTypeOrder, adapter.urlPathHelper, adapter.parameterName, adapter.defaultMediaType, bodyFile.getOriginalFilename());
HttpServletUtils.setContentTypeWithCharset(headers, contentType);
final HttpInputMessage newInputMessage = new HttpInputMessage() {
@Override
public InputStream getBody() throws IOException {
return bodyFile.getInputStream();
}
@Override
public HttpHeaders getHeaders() {
return headers;
}
};
for (final HttpMessageConverter<?> messageConverter : adapter.messageConverters) {
if (messageConverter.canRead(parameterClass, contentType)) {
return messageConverter.read(parameterClass, newInputMessage);
}
}
}
if (body == null) {
body = request.getParameter("body");
}
if (body != null) {
contentType = MediaTypeUtil.getRequestMediaType(request, adapter.mediaTypes, adapter.mediaTypeOrder, adapter.urlPathHelper, adapter.parameterName, adapter.defaultMediaType, "");
HttpServletUtils.setContentTypeWithCharset(headers, contentType);
byte[] bytes;
bytes = body.getBytes();
final InputStream bodyIn = new ByteArrayInputStream(bytes);
final HttpInputMessage newInputMessage = new HttpInputMessage() {
@Override
public InputStream getBody() throws IOException {
return bodyIn;
}
@Override
public HttpHeaders getHeaders() {
return headers;
}
};
for (final HttpMessageConverter<?> messageConverter : adapter.messageConverters) {
if (messageConverter.canRead(parameterClass, contentType)) {
return messageConverter.read(parameterClass, newInputMessage);
}
}
}
}
throw new HttpMediaTypeNotSupportedException(contentType, allSupportedMediaTypes);
} catch (final Exception e) {
return Exceptions.throwUncheckedException(e);
}
}, //
dataType, //
required, //
null);
}
use of org.springframework.web.multipart.MultipartHttpServletRequest in project tech by ffyyhh995511.
the class MultipleController method upload2.
/**
* 1:支持多文件上传
* 2:使用springMVC进行多文件的效率显然要比字符流写入方式效率上要高得多
* @param request
* @param response
* @return
* @throws IllegalStateException
* @throws IOException
*/
@RequestMapping("/upload")
public Object upload2(HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException {
// 创建一个通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
// 判断 request 是否有文件上传,即多部分请求
if (multipartResolver.isMultipart(request)) {
// 转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// 取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
while (iter.hasNext()) {
// 取得上传文件
MultipartFile file = multiRequest.getFile(iter.next());
if (file != null) {
// 取得当前上传文件的文件名称
String myFileName = file.getOriginalFilename();
// 如果名称不为“”,说明该文件存在,否则说明该文件不存在
if (myFileName.trim() != "") {
System.out.println(myFileName);
// 重命名上传后的文件名
String fileName = file.getOriginalFilename();
// 定义上传路径
String path = request.getSession().getServletContext().getRealPath("/upload") + fileName;
File localFile = new File(path);
file.transferTo(localFile);
}
}
}
}
return responseSuccess("test", new Date());
}
use of org.springframework.web.multipart.MultipartHttpServletRequest in project quick-media by liuyueyi.
the class BaseAction method getImg.
protected BufferedImage getImg(HttpServletRequest request) {
MultipartFile file = null;
if (request instanceof MultipartHttpServletRequest) {
file = ((MultipartHttpServletRequest) request).getFile("image");
}
if (file == null) {
try {
String image = request.getParameter("image");
if (StringUtils.isNotBlank(image) && !image.startsWith("/") && !image.startsWith("http")) {
image = ImgGenHelper.TMP_UPLOAD_PATH + image;
}
return ImageLoadUtil.getImageByPath(image);
} catch (IOException e) {
log.error("load upload image error! e: {}", e);
throw new IllegalArgumentException("图片不能为空!");
}
}
// 目前只支持 jpg, png, webp 等静态图片格式
String contentType = file.getContentType();
if (!MediaValidate.validateStaticImg(contentType)) {
throw new IllegalArgumentException("不支持的图片类型");
}
// 获取BufferedImage对象
try {
return ImageIO.read(file.getInputStream());
} catch (IOException e) {
log.error("WxImgCreateAction!Parse img from httpRequest to BuferedImage error! e: {}", e);
throw new IllegalArgumentException("不支持的图片类型!");
}
}
use of org.springframework.web.multipart.MultipartHttpServletRequest in project plumdo-work by wengwh.
the class ModelImportResource method importModel.
@PostMapping(value = "/models/import", name = "流程模型导入")
@ResponseStatus(value = HttpStatus.CREATED)
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public ModelResponse importModel(HttpServletRequest request) {
if (!(request instanceof MultipartHttpServletRequest)) {
exceptionFactory.throwIllegalArgument(ErrorConstant.REQUEST_NOT_MULTIPART);
}
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
if (multipartRequest.getFileMap().size() == 0) {
exceptionFactory.throwIllegalArgument(ErrorConstant.MULTIPART_CONTENT_EMPTY);
}
MultipartFile file = multipartRequest.getFileMap().values().iterator().next();
String fileName = file.getOriginalFilename();
if (fileName == null || (!fileName.endsWith(".bpmn") && !fileName.endsWith(".bpmn20.xml"))) {
exceptionFactory.throwIllegalArgument(ErrorConstant.FILE_NOT_BPMN, fileName);
}
try {
XMLInputFactory xif = XMLInputFactory.newInstance();
InputStreamReader xmlIn = new InputStreamReader(file.getInputStream(), "UTF-8");
XMLStreamReader xtr = xif.createXMLStreamReader(xmlIn);
BpmnModel bpmnModel = bpmnXmlConverter.convertToBpmnModel(xtr);
if (ObjectUtils.isEmpty(bpmnModel.getProcesses())) {
exceptionFactory.throwObjectNotFound(ErrorConstant.MODEL_NOT_FOUND_PROCESS, fileName);
}
Process process = bpmnModel.getMainProcess();
Model modelData = repositoryService.newModel();
modelData.setKey(process.getId());
Model lastModel = repositoryService.createModelQuery().modelKey(modelData.getKey()).latestVersion().singleResult();
if (lastModel == null) {
modelData.setVersion(TableConstant.MODEL_VESION_START);
} else {
modelData.setVersion(lastModel.getVersion() + 1);
}
if (ObjectUtils.isNotEmpty(process.getName())) {
modelData.setName(process.getName());
} else {
modelData.setName(process.getId());
}
ObjectNode metaInfo = new ObjectMapper().createObjectNode();
metaInfo.put("name", modelData.getName());
metaInfo.put("description", process.getDocumentation());
modelData.setMetaInfo(metaInfo.toString());
repositoryService.saveModel(modelData);
managementService.executeCommand(new SaveModelEditorCmd(modelData.getId(), bpmnJsonConverter.convertToJson(bpmnModel).toString()));
return restResponseFactory.createModelResponse(modelData);
} catch (Exception e) {
logger.error("导入流程文件异常", e);
exceptionFactory.throwDefinedException(ErrorConstant.MODEL_IMPORT_FILE_ERROR, fileName, e.getMessage());
}
return null;
}
Aggregations