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:serviceComposite.UserServiceComposite.java

@Override
public void updateProfilePicture(UserEntity user, MultipartFile file) {
    FileEntity oldProfilePicture = this.fileService.findProfilePicture(user);
    if (oldProfilePicture != null) {
        this.fileService.remove(oldProfilePicture);
        user = this.userDao.findById(user.getId());
    }/*w w w .ja  v  a2  s.  c om*/
    try {
        this.fileService.add(file.getOriginalFilename(), file.getContentType(), file.getBytes(), user, true);
    } catch (IOException e) {
    }
}

From source file:cz.zcu.kiv.eegdatabase.webservices.rest.datafile.DataFileServiceImpl.java

/**
 * Creates new DataFile under specified experiment.
 *
 * @param experimentId experiment identifier
 * @param description  data file description
 * @param file         data file multipart
 * @return identifier of created record/* ww w.  j a va  2  s  .c o m*/
 * @throws IOException error while creating record
 */
@Override
@Transactional
public int create(int experimentId, String description, MultipartFile file) throws IOException {
    DataFile datafile = new DataFile();
    datafile.setExperiment(experimentDao.getExperimentForDetail(experimentId));
    datafile.setDescription(description);
    datafile.setFilename(file.getOriginalFilename().replace(" ", "_"));
    datafile.setFileContent(Hibernate.createBlob(file.getBytes()));
    datafile.setMimetype(
            file.getContentType() != null ? file.getContentType().toLowerCase() : "application/octet-stream");

    //DB column size restriction
    if (datafile.getMimetype().length() > 40) {
        datafile.setMimetype("application/octet-stream");
    }
    return dataFileDao.create(datafile);
}

From source file:cn.newgxu.lab.info.controller.NoticeController.java

private void fileUpload(Notice info, String fileName, MultipartFile file) {
    try {//from   w w  w .  j av  a 2 s. c  om
        if (!file.isEmpty()) {
            uploadable(file);
            String originName = file.getOriginalFilename();
            Calendar now = Calendar.getInstance();
            String path = now.get(Calendar.YEAR) + "/" + (now.get(Calendar.MONTH) + 1);
            File dir = new File(Config.UPLOAD_ABSOLUTE_DIR + Config.UPLOAD_RELATIVE_DIR + path + "/");
            if (!dir.exists()) {
                if (!dir.mkdirs()) {
                    throw new RuntimeException("????");
                }
            }

            String savedFileName = now.getTimeInMillis() + RegexUtils.getFileExt(originName);
            file.transferTo(new File(dir.getAbsolutePath() + "/" + savedFileName));
            info.setDocUrl(Config.UPLOAD_RELATIVE_DIR + path + "/" + savedFileName);
            info.setDocName(fileName);
        }
    } catch (IllegalStateException e) {
        L.error("?", e);
        throw new RuntimeException("?", e);
    } catch (IOException e) {
        L.error("?", e);
        throw new RuntimeException("?", e);
    }
}

From source file:com.facerecog.rest.controller.RecognitionController.java

@RequestMapping(value = ApiUrls.URL_RECOG_UPLOAD_IMAGE, method = RequestMethod.POST)
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
    logger.info("File upload");

    if (!file.isEmpty()) {
        try {//from   w  w  w .  j ava2 s  .co m
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(new File(file.getOriginalFilename())));
            stream.write(bytes);
            stream.close();
            return "File uploaded: " + file.getOriginalFilename();
        } catch (Exception e) {
            return "Failed to upload image!";
        }
    } else {
        return "Failed to upload file because the file was empty.";
    }
}

From source file:org.opencron.server.controller.TerminalController.java

@RequestMapping("/upload")
public void upload(HttpSession httpSession, HttpServletResponse response, String token,
        @RequestParam(value = "file", required = false) MultipartFile[] file, String path) {
    TerminalClient terminalClient = TerminalSession.get(token);
    boolean success = true;
    if (terminalClient != null) {
        for (MultipartFile ifile : file) {
            String tmpPath = httpSession.getServletContext().getRealPath("/") + "upload" + File.separator;
            File tempFile = new File(tmpPath, ifile.getOriginalFilename());
            try {
                ifile.transferTo(tempFile);
                if (CommonUtils.isEmpty(path)) {
                    path = ".";
                } else if (path.endsWith("/")) {
                    path = path.substring(0, path.lastIndexOf("/"));
                }//from w w  w.  j a  va2  s.  co  m
                terminalClient.upload(tempFile.getAbsolutePath(), path + "/" + ifile.getOriginalFilename(),
                        ifile.getSize());
                tempFile.delete();
            } catch (Exception e) {
                success = false;
            }
        }
    }
    WebUtils.writeJson(response, success ? "true" : "false");
}

From source file:org.opensprout.osaf.propertyeditor.FilePropertyEditor.java

/** MultipartFile -> File(uploadFolder/filename) */
public void setValue(Object value) {
    if (value instanceof MultipartFile) {
        MultipartFile multipartFile = (MultipartFile) value;

        // if there is no file
        if (multipartFile.isEmpty()) {
            this.logger.debug("Filename: null");
            super.setValue(null);
            return;
        }//from w  w w  . j av a2  s.c  o m

        String fileName = makeDuplicationSafeFileName(multipartFile.getOriginalFilename());
        this.logger.debug("Filename : " + fileName);
        String path = uploadDirectory + "/" + fileName;

        // transfer file
        try {
            multipartFile.transferTo(new File(path));
        } catch (IOException e) {
            this.logger.debug("Multipart Error : " + e.getMessage());
            throw new OSAFException("Check upload folder  : [" + uploadDirectory + "]."
                    + "Nested exception is : " + e.getMessage());
        }
        super.setValue(path);
    } else {
        super.setValue(null);
    }
}

From source file:ua.aits.crc.controller.SystemController.java

@RequestMapping(value = { "/system/do/uploadfile", "/system/do/uploadfile/" }, method = RequestMethod.POST)
public @ResponseBody String uploadFileHandler(@RequestParam("file") MultipartFile file,
        @RequestParam("path") String path, HttpServletRequest request) {
    String name = file.getOriginalFilename();
    if (!file.isEmpty()) {
        try {//from  w w  w  . ja va2  s. c o m
            byte[] bytes = file.getBytes();
            File dir = new File(Constants.home + path);
            if (!dir.exists())
                dir.mkdirs();
            File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
            try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) {
                stream.write(bytes);
            }
            return "";
        } catch (Exception e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name + " because the file was empty.";
    }
}

From source file:ua.aits.crc.controller.SystemController.java

@RequestMapping(value = { "/system/do/uploadimage", "/system/do/uploadimage/" }, method = RequestMethod.POST)
public @ResponseBody String uploadImageHandler(@RequestParam("file") MultipartFile file,
        @RequestParam("path") String path, HttpServletRequest request) {
    String name = file.getOriginalFilename();
    name = TransliteratorClass.transliterate(name);
    if (!file.isEmpty()) {
        try {/*ww w . java2s.  c  o m*/
            byte[] bytes = file.getBytes();
            File dir = new File(Constants.home + path);
            if (!dir.exists())
                dir.mkdirs();
            File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
            try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) {
                stream.write(bytes);
            }
            return "";
        } catch (Exception e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name + " because the file was empty.";
    }
}

From source file:fr.xebia.cocktail.CocktailManager.java

/**
 * TODO use PUT instead of POST/*from w  w w .  j  av a 2s .co  m*/
 *
 * @param id    id of the cocktail
 * @param photo to associate with the cocktail
 * @return redirection to display cocktail
 */
@RequestMapping(value = "/cocktail/{id}/photo", method = RequestMethod.POST)
public String updatePhoto(@PathVariable String id, @RequestParam("photo") MultipartFile photo) {

    if (!photo.isEmpty()) {
        try {
            String contentType = fileStorageService.findContentType(photo.getOriginalFilename());
            if (contentType == null) {
                logger.warn("photo",
                        "Skip file with unsupported extension '" + photo.getOriginalFilename() + "'");
            } else {

                InputStream photoInputStream = photo.getInputStream();
                long photoSize = photo.getSize();

                Map metadata = new TreeMap();
                metadata.put("Content-Length", Arrays.asList(new String[] { "" + photoSize }));
                metadata.put("Content-Type", Arrays.asList(new String[] { contentType }));
                metadata.put("Cache-Control", Arrays.asList(
                        new String[] { "public, max-age=" + TimeUnit.SECONDS.convert(365, TimeUnit.DAYS) }));

                /*    ObjectMetadata objectMetadata = new ObjectMetadata();
                    objectMetadata.setContentLength(photoSize);
                    objectMetadata.setContentType(contentType);
                    objectMetadata.setCacheControl("public, max-age=" + TimeUnit.SECONDS.convert(365, TimeUnit.DAYS));*/
                String photoUrl = fileStorageService.storeFile(photo.getBytes(), metadata);

                Cocktail cocktail = cocktailRepository.get(id);
                logger.info("Saved {}", photoUrl);
                cocktail.setPhotoUrl(photoUrl);
                cocktailRepository.update(cocktail);
            }

        } catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }
    return "redirect:/cocktail/" + id;
}

From source file:org.openmrs.module.iqchartimport.web.controller.UploadController.java

@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.POST)
public String handleSubmit(HttpServletRequest request, ModelMap model) {
    Utils.checkSuperUser();/*from  w  w  w.  j  av  a 2s.co m*/

    DefaultMultipartHttpServletRequest multipart = (DefaultMultipartHttpServletRequest) request;
    MultipartFile uploadFile = multipart.getFile("mdbfile");

    IQChartDatabase.clearInstance();

    // Process uploaded database if there is one
    if (uploadFile != null) {
        try {
            // Copy uploaded MDB to temp file
            File tempMDBFile = File.createTempFile(uploadFile.getOriginalFilename(), ".temp");
            uploadFile.transferTo(tempMDBFile);

            // Store uploaded database as singleton
            IQChartDatabase.createInstance(uploadFile.getOriginalFilename(), tempMDBFile.getAbsolutePath());

        } catch (IOException e) {
            model.put("uploaderror", "Unable to upload database file");
        }
    }

    return showForm(request, model);
}