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.jayway.restassured.examples.springmvc.controller.FileUploadController.java

@RequestMapping(value = "/fileUpload2", method = POST, consumes = MULTIPART_FORM_DATA_VALUE, produces = APPLICATION_JSON_VALUE)
public @ResponseBody String fileUpload2(@RequestParam(value = "controlName") MultipartFile file) {
    return "{ \"size\" : " + file.getSize() + ", \"name\" : \"" + file.getName() + "\", \"originalName\" : \""
            + file.getOriginalFilename() + "\", \"mimeType\" : \"" + file.getContentType() + "\" }";
}

From source file:com.github.wxiaoqi.oss.controller.OssController.java

/**
 * //from w w  w .j av a2 s  . c  om
 */
@RequestMapping("/upload")
public ObjectRestResponse<String> upload(@RequestParam("file") MultipartFile file) throws Exception {
    if (file.isEmpty()) {
        throw new BaseException("?");
    }
    //
    String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
    String url = ossFactory.build().uploadSuffix(file.getBytes(), suffix);
    return new ObjectRestResponse<>().data(url);
}

From source file:se.gothiaforum.validator.actorsform.ImageValidator.java

/**
 * Validate if the image have valid size, file suffix and mime.
 * //  www.j a  va  2  s  .c  o m
 * @param multipartFile
 *            the multipart file
 * @param errors
 *            the errors
 */
public void validate(MultipartFile multipartFile, List<String> errors) {

    if (multipartFile.getSize() > IMAGE_MIN_SIZE && multipartFile.getSize() < IMAGE_MAX_SIZE) {
        String originalFileName = multipartFile.getOriginalFilename();

        String contentType = multipartFile.getContentType();

        if (!"image/jpeg".equals(contentType) && !"image/png".equals(contentType)
                && !"image/x-png".equals(contentType) && !"image/pjpeg".equals(contentType)
                && !"image/gif".equals(contentType)) {
            errors.add("wrong-type-of-content-type");
        }

        int fileExtensionIndex = originalFileName.lastIndexOf(".");
        String fileExtension = originalFileName.substring((fileExtensionIndex + 1), originalFileName.length());

        if (!fileExtension.equals("png") && !fileExtension.equals("jpg") && !fileExtension.equals("gif")) {
            errors.add("wrong-type-of-file-extension");
        }

    } else {
        errors.add("wrong-size-on-file");
    }
}

From source file:com.cami.web.controller.FileController.java

private String getFileName(MultipartFile file, AppelOffre appelOffre) {
    String ext = FilenameUtils.getExtension(file.getOriginalFilename());
    String saveName = appelOffre.getId() + "_" + new Date().getTime() + "." + ext;
    return saveName;

}

From source file:com.ineunet.knife.upload.controller.UploadController.java

@RequestMapping(value = "doUpload", method = RequestMethod.POST)
public @ResponseBody String doUpload(HttpServletRequest request, @RequestParam(value = "field") String field)
        throws IOException {
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
    WebPaths.init(request);//w  w w .  j a v  a 2  s  . c o  m
    String rootPath = WebPaths.getRootPath();
    String column = ClassStrUtils.hump2Underline(field);

    // If associatedId is null or 0, generate one.
    Long associatedId = this.getService().validateId(column, null);
    String fileName = "";
    for (Map.Entry<String, MultipartFile> uf : fileMap.entrySet()) {
        MultipartFile mf = uf.getValue();
        String originalName = mf.getOriginalFilename();
        this.getService().setOriginalFileName(column, associatedId, originalName);
        if (!UploadUtils.checkFileType(originalName)) {
            throw new RuntimeException("unsupported file type");
        }

        fileName = UploadUtils.buildTempFileName(this.getService().tableName(), column, associatedId,
                originalName);
        String key = this.getService().getKey(column, associatedId);
        this.getService().setTempFileName(key, fileName);

        // copy file
        String tempPath = rootPath + UploadUtils.TEMP_PATH_PART;
        File file = new File(tempPath + fileName);
        FileCopyUtils.copy(mf.getBytes(), file);

        this.getService().setTempContent(mf.getBytes(), column, associatedId);
        break;
    }
    return fileName;
}

From source file:aiai.ai.launchpad.snippet.SnippetController.java

@PostMapping(value = "/snippet-upload-from-file")
public String uploadSnippet(MultipartFile file, final RedirectAttributes redirectAttributes) {

    String originFilename = file.getOriginalFilename();
    if (originFilename == null) {
        redirectAttributes.addFlashAttribute("errorMessage", "#422.01 name of uploaded file is null");
        return "redirect:/launchpad/snippets";
    }/* w  w  w. j a v  a 2 s.com*/
    int idx;
    if ((idx = originFilename.lastIndexOf('.')) == -1) {
        redirectAttributes.addFlashAttribute("errorMessage",
                "#422.02 '.' wasn't found, bad filename: " + originFilename);
        return "redirect:/launchpad/snippets";
    }
    String ext = originFilename.substring(idx).toLowerCase();
    if (!".zip".equals(ext)) {
        redirectAttributes.addFlashAttribute("errorMessage",
                "#422.03 only '.zip' files is supported, filename: " + originFilename);
        return "redirect:/launchpad/snippets";
    }

    final String location = System.getProperty("java.io.tmpdir");

    try {
        File tempDir = DirUtils.createTempDir("snippet-upload-");
        if (tempDir == null || tempDir.isFile()) {
            redirectAttributes.addFlashAttribute("errorMessage",
                    "#422.04 can't create temporary directory in " + location);
            return "redirect:/launchpad/snippets";
        }
        final File zipFile = new File(tempDir, "snippet.zip");
        log.debug("Start storing an uploaded snippet to disk");
        try (OutputStream os = new FileOutputStream(zipFile)) {
            IOUtils.copy(file.getInputStream(), os, 64000);
        }
        log.debug("Start unzipping archive");
        ZipUtils.unzipFolder(zipFile, tempDir);
        log.debug("Start loading snippet data to db");
        snippetService.loadSnippetsRecursively(tempDir);
    } catch (Exception e) {
        log.error("Error", e);
        redirectAttributes.addFlashAttribute("errorMessage",
                "#422.05 can't load snippets, Error: " + e.toString());
        return "redirect:/launchpad/snippets";
    }

    log.debug("All done. Send redirect");
    return "redirect:/launchpad/snippets";
}

From source file:com.baifendian.swordfish.webserver.service.storage.FileSystemStorageService.java

/**
 * ?, /*from   www  . j  a v  a2 s  .  com*/
 *
 * @param file
 * @param destFilename
 */
@Override
public void store(MultipartFile file, String destFilename) {
    try {
        if (file.isEmpty()) {
            throw new StorageException("Failed to store empty file " + file.getOriginalFilename());
        }

        File destFile = new File(destFilename);
        File destDir = new File(destFile.getParent());

        if (!destDir.exists()) {
            FileUtils.forceMkdir(destDir);
        }

        Files.copy(file.getInputStream(), Paths.get(destFilename));
    } catch (IOException e) {
        throw new StorageException("Failed to store file " + file.getOriginalFilename(), e);
    }
}

From source file:it.cilea.osd.jdyna.controller.FormTabController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {
    T object = (T) command;/*from   ww  w .j  ava2 s  . co m*/

    String deleteImage_s = request.getParameter("deleteIcon");

    if (deleteImage_s != null) {
        Boolean deleteImage = Boolean.parseBoolean(deleteImage_s);
        if (deleteImage) {
            removeTabIcon(object);
        }
    }

    boolean createEditTab = false;
    if (object.getId() == null) {
        createEditTab = true;
    }
    applicationService.saveOrUpdate(tabClass, object);

    MultipartFile itemIcon = object.getIconFile();

    // if there is a remote url we don't upload the file
    if (itemIcon != null && !itemIcon.getOriginalFilename().isEmpty()) {
        loadTabIcon(object, object.getId().toString(), object.getIconFile());
        applicationService.saveOrUpdate(tabClass, object);
    }
    if (createEditTab) {
        createEditTab(object);
    }

    String shortName = Utils.getAdminSpecificPath(request, null);
    return new ModelAndView(getSuccessView() + "?path=" + shortName);
}

From source file:it.cilea.osd.jdyna.controller.FormEditTabController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {
    ET object = (ET) command;/*from   ww  w . j  a  v  a  2  s  .c  o m*/

    String deleteImage_s = request.getParameter("deleteIcon");

    if (deleteImage_s != null) {
        Boolean deleteImage = Boolean.parseBoolean(deleteImage_s);
        if (deleteImage) {
            removeTabIcon(object);
        }
    }

    applicationService.saveOrUpdate(tabEditClass, object);

    MultipartFile itemIcon = object.getIconFile();

    // if there is a remote url we don't upload the file 
    if (itemIcon != null && !itemIcon.getOriginalFilename().isEmpty()) {
        loadTabIcon(object, object.getId().toString(), object.getIconFile());
        applicationService.saveOrUpdate(tabEditClass, object);
    }
    String shortName = Utils.getAdminSpecificPath(request, null);
    return new ModelAndView(getSuccessView() + "?path=" + shortName);
}

From source file:com.persistent.cloudninja.validator.LogoFileDTOValidator.java

/**
 * validates the multipart file./*from w ww  .ja  v a  2s .  co m*/
 * 
 * @param target : LogoFile object.
 * @param errors : stores and exposes validation errors.
 * 
 */
@Override
public void validate(Object target, Errors errors) {
    LogoFileDTO logoFile = (LogoFileDTO) target;
    MultipartFile file = logoFile.getFile(); // file should be of gif, png, bmp, jpeg, jpg type
    if (file.isEmpty()) {
        errors.rejectValue("file", "Invalid file", "File cannot be empty");
    } else if (!(file.getOriginalFilename().endsWith(".gif") | file.getOriginalFilename().endsWith(".png")
            | file.getOriginalFilename().endsWith(".bmp") | file.getOriginalFilename().endsWith(".jpeg")
            | file.getOriginalFilename().endsWith(".jpg"))) {
        errors.rejectValue("file", "Invalid file", "File should be a valid gif,png, bmp, jpeg or jpg file.");
    } else if (logoFile.getFile().getSize() > 200 * 1024) {
        errors.rejectValue("file", "Invalid file", "File size should be less then 200KB.");
    }
}