Example usage for org.springframework.web.multipart MultipartFile getOriginalFilename

List of usage examples for org.springframework.web.multipart MultipartFile getOriginalFilename

Introduction

In this page you can find the example usage for org.springframework.web.multipart MultipartFile getOriginalFilename.

Prototype

@Nullable
String getOriginalFilename();

Source Link

Document

Return the original filename in the client's filesystem.

Usage

From source file:com.gothiaforum.validator.actorsform.ImageValidatorTest.java

/**
 * Test with wrong filename and wrong content type.
 * /*  w  w w  .java2s  . c  o  m*/
 * @throws Exception
 *             the exception
 */
@Test
public void test6() throws Exception {

    ImageValidator imageValidator = new ImageValidator();

    List<String> errors = new ArrayList<String>();
    MultipartFile multipartFile = Mockito.mock(MultipartFile.class);

    Mockito.when(multipartFile.getSize()).thenReturn((long) (1 * 1024 * 1024));
    Mockito.when(multipartFile.getOriginalFilename()).thenReturn("my-image.pizza");
    Mockito.when(multipartFile.getContentType()).thenReturn("image/pizza");

    imageValidator.validate(multipartFile, errors);

    assertEquals(2, errors.size());

}

From source file:org.ktunaxa.referral.server.mvc.UploadDocumentController.java

@RequestMapping(value = "/upload/referral/document", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam(KtunaxaConstant.FORM_ID) String formId,
        @RequestParam(KtunaxaConstant.FORM_REFERRAL) String referralId,
        @RequestParam(value = KtunaxaConstant.FORM_OVERRIDE, required = false) String override,
        @RequestParam("file") MultipartFile file, Model model) {

    UploadResponse response = new UploadResponse();
    response.addObject(KtunaxaConstant.FORM_ID, formId);
    try {/*ww w.j a  v  a2s  . co  m*/
        String year = "20" + referralId.substring(8, 10);
        String originalFilename = file.getOriginalFilename();
        Document document;
        if (override != null && "true".equalsIgnoreCase(override)) {
            document = cmisService.saveOrUpdate(originalFilename, file.getContentType(), file.getInputStream(),
                    file.getSize(), year, referralId);
        } else {
            document = cmisService.create(originalFilename, file.getContentType(), file.getInputStream(),
                    file.getSize(), year, referralId);
        }
        response.addObject(KtunaxaConstant.FORM_DOCUMENT_TITLE, originalFilename);
        response.addObject(KtunaxaConstant.FORM_DOCUMENT_ID, document.getId());
        response.addObject(KtunaxaConstant.FORM_DOCUMENT_DISPLAY_URL, cmisService.getDisplayUrl(document));
        response.addObject(KtunaxaConstant.FORM_DOCUMENT_DOWNLOAD_URL, cmisService.getDownloadUrl(document));
        model.addAttribute(UploadView.RESPONSE, response);
    } catch (Exception e) {
        log.error("Could not upload document", e);
        response.setException(e);
    }
    model.addAttribute(UploadView.RESPONSE, response);
    return UploadView.NAME;
}

From source file:com.iisigroup.cap.sample.handler.SampleHandler.java

@HandlerType(HandlerTypeEnum.FileUpload)
public IResult upload(IRequest request) throws CapException {
    AjaxFormResult result = new AjaxFormResult();
    // String str = request.get("testStr");
    MultipartFile f = request.getFile("ufile");
    try {/*from   w  ww  .  ja  va  2  s .  c o  m*/
        FileUtils.writeByteArrayToFile(new File("xxxx.txt"), f.getBytes());
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    String fileName = f.getOriginalFilename();
    result.set(Constants.AJAX_NOTIFY_MESSAGE, fileName + " upload file success!!");
    return result;
}

From source file:com.artivisi.belajar.restful.ui.controller.ApplicationConfigController.java

@RequestMapping(value = "/config/upload", method = RequestMethod.POST)
@ResponseBody//from www  . ja v  a2  s .  co  m
public List<Map<String, String>> testUpload(
        @RequestParam(value = "uploadedfiles[]") List<MultipartFile> daftarFoto) throws Exception {

    logger.debug("Jumlah file yang diupload {}", daftarFoto.size());

    List<Map<String, String>> hasil = new ArrayList<Map<String, String>>();

    for (MultipartFile multipartFile : daftarFoto) {
        logger.debug("Nama File : {}", multipartFile.getName());
        logger.debug("Nama File Original : {}", multipartFile.getOriginalFilename());
        logger.debug("Ukuran File : {}", multipartFile.getSize());

        Map<String, String> keterangan = new HashMap<String, String>();
        keterangan.put("Nama File", multipartFile.getOriginalFilename());
        keterangan.put("Ukuran File", Long.valueOf(multipartFile.getSize()).toString());
        keterangan.put("Content Type", multipartFile.getContentType());
        keterangan.put("UUID", UUID.randomUUID().toString());
        File temp = File.createTempFile("xxx", "xxx");
        multipartFile.transferTo(temp);
        keterangan.put("MD5", createMD5Sum(temp));
        hasil.add(keterangan);
    }

    return hasil;
}

From source file:org.flowable.ui.modeler.service.FlowableModelQueryService.java

public ModelRepresentation importCaseModel(HttpServletRequest request, MultipartFile file) {

    String fileName = file.getOriginalFilename();
    if (fileName != null && (fileName.endsWith(".cmmn") || fileName.endsWith(".cmmn.xml"))) {
        try {/*  w w  w .j a  va  2  s.c o m*/
            XMLInputFactory xif = XmlUtil.createSafeXmlInputFactory();
            InputStreamReader xmlIn = new InputStreamReader(file.getInputStream(), "UTF-8");
            XMLStreamReader xtr = xif.createXMLStreamReader(xmlIn);
            CmmnModel cmmnModel = cmmnXmlConverter.convertToCmmnModel(xtr);
            if (CollectionUtils.isEmpty(cmmnModel.getCases())) {
                throw new BadRequestException("No cases found in definition " + fileName);
            }

            if (cmmnModel.getLocationMap().size() == 0) {
                throw new BadRequestException("No CMMN DI found in definition " + fileName);
            }

            ObjectNode modelNode = cmmnJsonConverter.convertToJson(cmmnModel);

            Case caseModel = cmmnModel.getPrimaryCase();
            String name = caseModel.getId();
            if (StringUtils.isNotEmpty(caseModel.getName())) {
                name = caseModel.getName();
            }
            String description = caseModel.getDocumentation();

            ModelRepresentation model = new ModelRepresentation();
            model.setKey(caseModel.getId());
            model.setName(name);
            model.setDescription(description);
            model.setModelType(AbstractModel.MODEL_TYPE_CMMN);
            Model newModel = modelService.createModel(model, modelNode.toString(),
                    SecurityUtils.getCurrentUserObject());
            return new ModelRepresentation(newModel);

        } catch (BadRequestException e) {
            throw e;

        } catch (Exception e) {
            LOGGER.error("Import failed for {}", fileName, e);
            throw new BadRequestException(
                    "Import failed for " + fileName + ", error message " + e.getMessage());
        }
    } else {
        throw new BadRequestException(
                "Invalid file name, only .cmmn and .cmmn.xml files are supported not " + fileName);
    }
}

From source file:org.flowable.ui.modeler.service.FlowableModelQueryService.java

public ModelRepresentation importProcessModel(HttpServletRequest request, MultipartFile file) {

    String fileName = file.getOriginalFilename();
    if (fileName != null && (fileName.endsWith(".bpmn") || fileName.endsWith(".bpmn20.xml"))) {
        try {/*  ww  w  . j  av a2s .c o  m*/
            XMLInputFactory xif = XmlUtil.createSafeXmlInputFactory();
            InputStreamReader xmlIn = new InputStreamReader(file.getInputStream(), "UTF-8");
            XMLStreamReader xtr = xif.createXMLStreamReader(xmlIn);
            BpmnModel bpmnModel = bpmnXmlConverter.convertToBpmnModel(xtr);
            if (CollectionUtils.isEmpty(bpmnModel.getProcesses())) {
                throw new BadRequestException("No process found in definition " + fileName);
            }

            if (bpmnModel.getLocationMap().size() == 0) {
                BpmnAutoLayout bpmnLayout = new BpmnAutoLayout(bpmnModel);
                bpmnLayout.execute();
            }

            ObjectNode modelNode = bpmnJsonConverter.convertToJson(bpmnModel);

            org.flowable.bpmn.model.Process process = bpmnModel.getMainProcess();
            String name = process.getId();
            if (StringUtils.isNotEmpty(process.getName())) {
                name = process.getName();
            }
            String description = process.getDocumentation();

            ModelRepresentation model = new ModelRepresentation();
            model.setKey(process.getId());
            model.setName(name);
            model.setDescription(description);
            model.setModelType(AbstractModel.MODEL_TYPE_BPMN);
            Model newModel = modelService.createModel(model, modelNode.toString(),
                    SecurityUtils.getCurrentUserObject());
            return new ModelRepresentation(newModel);

        } catch (BadRequestException e) {
            throw e;

        } catch (Exception e) {
            LOGGER.error("Import failed for {}", fileName, e);
            throw new BadRequestException(
                    "Import failed for " + fileName + ", error message " + e.getMessage());
        }
    } else {
        throw new BadRequestException(
                "Invalid file name, only .bpmn and .bpmn20.xml files are supported not " + fileName);
    }
}

From source file:com.web.controller.ToolController.java

@ResponseBody
@RequestMapping(value = "/tool/verifyapk", method = RequestMethod.POST)
public String verifyApk(@RequestParam("apkfile") MultipartFile file) {

    //keytool -list -printcert -jarfile d:\weixin653android980.apk
    //keytool -printcert -file D:\testapp\META-INF\CERT.RSA
    //System.out.println("12345");
    try {/*  ww  w . ja  va  2  s.com*/
        OutputStream stream = new FileOutputStream(new File(file.getOriginalFilename()));
        BufferedOutputStream outputStream = new BufferedOutputStream(stream);
        outputStream.write(file.getBytes());
        outputStream.flush();
        outputStream.close();

        Runtime runtime = Runtime.getRuntime();
        String ccString = "keytool -list -printcert -jarfile C:\\Users\\Administrator\\Desktop\\zju1.1.8.2.apk";
        Process p = runtime.exec(ccString);

        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

        StringBuilder sb = new StringBuilder();
        while (br.readLine() != null) {
            sb.append(br.readLine() + "<br/>");
        }
        p.destroy();
        p = null;
        return sb.toString();
    } catch (FileNotFoundException fe) {
        return fe.getMessage();
    } catch (IOException ioe) {
        return ioe.getMessage();
    }

}

From source file:com.haulmont.restapi.controllers.FileUploadController.java

/**
 * Method for multipart file upload. It expects the file contents to be passed in the part called 'file'
 *//*from  w  w w  .  j a  v a  2  s. c o  m*/
@PostMapping(consumes = "multipart/form-data")
public ResponseEntity<FileInfo> uploadFile(@RequestParam("file") MultipartFile file,
        @RequestParam(required = false) String name, HttpServletRequest request) {
    try {
        if (Strings.isNullOrEmpty(name)) {
            name = file.getOriginalFilename();
        }

        long size = file.getSize();
        FileDescriptor fd = createFileDescriptor(name, size);

        InputStream is = file.getInputStream();
        uploadToMiddleware(is, fd);
        saveFileDescriptor(fd);

        return createFileInfoResponseEntity(request, fd);
    } catch (Exception e) {
        log.error("File upload failed", e);
        throw new RestAPIException("File upload failed", "File upload failed",
                HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.biopax.validator.ws.ValidatorController.java

/**
 * JSP pages and RESTful web services controller, the main one that checks BioPAX data.
 * All parameter names are important, i.e., these are part of public API (for clients)
 * // w  w  w. j a  v  a2s .c  om
 * Framework's built-in parameters:
 * @param request the web request object (may contain multi-part data, i.e., multiple files uploaded)
 * @param response 
 * @param mvcModel Spring MVC Model
 * @param writer HTTP response writer
 * 
 * BioPAX Validator/Normalizer query parameters:
 * @param url
 * @param retDesired
 * @param autofix
 * @param filter
 * @param maxErrors
 * @param profile
 * @param normalizer binds to three boolean options: normalizer.fixDisplayName, normalizer.inferPropertyOrganism, normalizer.inferPropertyDataSource
 * @return
 * @throws IOException
 */
@RequestMapping(value = "/check", method = RequestMethod.POST)
public String check(HttpServletRequest request, HttpServletResponse response, Model mvcModel, Writer writer,
        @RequestParam(required = false) String url, @RequestParam(required = false) String retDesired,
        @RequestParam(required = false) Boolean autofix, @RequestParam(required = false) Behavior filter,
        @RequestParam(required = false) Integer maxErrors, @RequestParam(required = false) String profile,
        //normalizer!=null when called from the JSP; 
        //but it's usually null when from the validator-client or a web script
        @ModelAttribute("normalizer") Normalizer normalizer) throws IOException {
    Resource resource = null; // a resource to validate

    // create the response container
    ValidatorResponse validatorResponse = new ValidatorResponse();

    if (url != null && url.length() > 0) {
        if (url != null)
            log.info("url : " + url);
        try {
            resource = new UrlResource(url);
        } catch (MalformedURLException e) {
            mvcModel.addAttribute("error", e.toString());
            return "check";
        }

        try {
            Validation v = execute(resource, resource.getDescription(), maxErrors, autofix, filter, profile,
                    normalizer);
            validatorResponse.addValidationResult(v);
        } catch (Exception e) {
            return errorResponse(mvcModel, "check", "Exception: " + e);
        }

    } else if (request instanceof MultipartHttpServletRequest) {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        Map files = multiRequest.getFileMap();
        Assert.state(!files.isEmpty(), "No files to validate");
        for (Object o : files.values()) {
            MultipartFile file = (MultipartFile) o;
            String filename = file.getOriginalFilename();
            // a workaround (for some reason there is always a no-name-file;
            // this might be a javascript isue)
            if (file.getBytes().length == 0 || filename == null || "".equals(filename))
                continue;

            log.info("check : " + filename);

            resource = new ByteArrayResource(file.getBytes());

            try {
                Validation v = execute(resource, filename, maxErrors, autofix, filter, profile, normalizer);
                validatorResponse.addValidationResult(v);
            } catch (Exception e) {
                return errorResponse(mvcModel, "check", "Exception: " + e);
            }

        }
    } else {
        return errorResponse(mvcModel, "check", "No BioPAX input source provided!");
    }

    if ("xml".equalsIgnoreCase(retDesired)) {
        response.setContentType("application/xml");
        ValidatorUtils.write(validatorResponse, writer, null);
    } else if ("html".equalsIgnoreCase(retDesired)) {
        /* could also use ValidatorUtils.write with a xml-to-html xslt source
         but using JSP here makes it easier to keep the same style, header, footer*/
        mvcModel.addAttribute("response", validatorResponse);
        return "groupByCodeResponse";
    } else { // owl only
        response.setContentType("text/plain");
        // write all the OWL results one after another TODO any better solution?
        for (Validation result : validatorResponse.getValidationResult()) {
            if (result.getModelData() != null)
                writer.write(result.getModelData() + NEWLINE);
            else
                // empty result
                writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<rdf:RDF></rdf:RDF>" + NEWLINE);
        }
    }

    return null; // (Writer is used instead)
}

From source file:com.vsquaresystem.safedeals.marketprice.MarketPriceService.java

@Transactional(readOnly = false)
public Boolean insertAttachments(MultipartFile attachmentMultipartFile)
        throws JsonProcessingException, IOException {
    File outputFile = attachmentUtils.storeAttachmentByAttachmentType(
            attachmentMultipartFile.getOriginalFilename(), attachmentMultipartFile.getInputStream(),
            AttachmentUtils.AttachmentType.MARKET_PRICE);
    return outputFile.exists();
}