Search in sources :

Example 36 with MultipartHttpServletRequest

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);
}
Also used : MultipartFile(org.springframework.web.multipart.MultipartFile) MultipartHttpServletRequest(org.springframework.web.multipart.MultipartHttpServletRequest)

Example 37 with MultipartHttpServletRequest

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);
}
Also used : ServletServerHttpRequest(org.springframework.http.server.ServletServerHttpRequest) HttpHeaders(org.springframework.http.HttpHeaders) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) ArrayList(java.util.ArrayList) HttpMediaTypeNotSupportedException(org.springframework.web.HttpMediaTypeNotSupportedException) MultipartFile(org.springframework.web.multipart.MultipartFile) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) DataType(com.revolsys.datatype.DataType) MediaType(org.springframework.http.MediaType) RequestBody(org.springframework.web.bind.annotation.RequestBody) HttpInputMessage(org.springframework.http.HttpInputMessage) InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Charset(java.nio.charset.Charset) IOException(java.io.IOException) WrappedException(com.revolsys.util.WrappedException) IOException(java.io.IOException) HttpMediaTypeNotSupportedException(org.springframework.web.HttpMediaTypeNotSupportedException) ByteArrayInputStream(java.io.ByteArrayInputStream) MultipartHttpServletRequest(org.springframework.web.multipart.MultipartHttpServletRequest)

Example 38 with MultipartHttpServletRequest

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());
}
Also used : MultipartFile(org.springframework.web.multipart.MultipartFile) CommonsMultipartResolver(org.springframework.web.multipart.commons.CommonsMultipartResolver) File(java.io.File) MultipartFile(org.springframework.web.multipart.MultipartFile) Date(java.util.Date) MultipartHttpServletRequest(org.springframework.web.multipart.MultipartHttpServletRequest) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 39 with MultipartHttpServletRequest

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("不支持的图片类型!");
    }
}
Also used : MultipartFile(org.springframework.web.multipart.MultipartFile) IOException(java.io.IOException) MultipartHttpServletRequest(org.springframework.web.multipart.MultipartHttpServletRequest)

Example 40 with MultipartHttpServletRequest

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;
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) InputStreamReader(java.io.InputStreamReader) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Process(org.flowable.bpmn.model.Process) SaveModelEditorCmd(com.plumdo.flow.cmd.SaveModelEditorCmd) BpmnModel(org.flowable.bpmn.model.BpmnModel) MultipartFile(org.springframework.web.multipart.MultipartFile) Model(org.flowable.engine.repository.Model) BpmnModel(org.flowable.bpmn.model.BpmnModel) XMLInputFactory(javax.xml.stream.XMLInputFactory) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) MultipartHttpServletRequest(org.springframework.web.multipart.MultipartHttpServletRequest) PostMapping(org.springframework.web.bind.annotation.PostMapping) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

MultipartHttpServletRequest (org.springframework.web.multipart.MultipartHttpServletRequest)44 MultipartFile (org.springframework.web.multipart.MultipartFile)29 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)14 File (java.io.File)11 ActivitiIllegalArgumentException (org.activiti.engine.ActivitiIllegalArgumentException)10 ActivitiException (org.activiti.engine.ActivitiException)8 PostMapping (org.springframework.web.bind.annotation.PostMapping)8 ArrayList (java.util.ArrayList)7 IOException (java.io.IOException)6 ActivitiObjectNotFoundException (org.activiti.engine.ActivitiObjectNotFoundException)6 ResponseStatus (org.springframework.web.bind.annotation.ResponseStatus)6 HashMap (java.util.HashMap)5 RestVariable (org.activiti.rest.service.api.engine.variable.RestVariable)5 DataGridException (com.emc.metalnx.core.domain.exceptions.DataGridException)2 OptUploadFileRespDto (com.paascloud.provider.model.dto.oss.OptUploadFileRespDto)2 ApiOperation (io.swagger.annotations.ApiOperation)2 FileNotFoundException (java.io.FileNotFoundException)2 InputStreamReader (java.io.InputStreamReader)2 Date (java.util.Date)2 List (java.util.List)2