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:org.broadleafcommerce.admin.util.controllers.FileUploadController.java

protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws ServletException, IOException {

    // cast the bean
    FileUploadBean bean = (FileUploadBean) command;

    // let's see if there's content there
    MultipartFile file = bean.getFile();
    if (file == null) {
        // hmm, that's strange, the user did not upload anything
    }/*from  ww  w .  j ava 2  s .  c  o m*/

    try {
        String basepath = request.getPathTranslated().substring(0,
                request.getPathTranslated().indexOf(File.separator + "upload"));
        String absoluteFilename = basepath + File.separator + bean.getDirectory() + File.separator
                + file.getOriginalFilename();
        FileSystemResource fileResource = new FileSystemResource(absoluteFilename);

        checkDirectory(basepath + File.separator + bean.getDirectory());

        backupExistingFile(fileResource, basepath + bean.getDirectory());

        FileOutputStream fout = new FileOutputStream(new FileSystemResource(
                basepath + File.separator + bean.getDirectory() + File.separator + file.getOriginalFilename())
                        .getFile());
        BufferedOutputStream bout = new BufferedOutputStream(fout);
        BufferedInputStream bin = new BufferedInputStream(file.getInputStream());
        int x;
        while ((x = bin.read()) != -1) {
            bout.write(x);
        }
        bout.flush();
        bout.close();
        bin.close();
        return super.onSubmit(request, response, command, errors);
    } catch (Exception e) {
        //Exception occured;
        e.printStackTrace();
        throw new RuntimeException(e);
        // return null;                
    }
}

From source file:org.pdfgal.pdfgalweb.services.impl.BookmarkServiceImpl.java

@Override
public DownloadForm addBookmarks(final MultipartFile file, final String title, final List<Integer> pagesList,
        final List<String> textsList, final HttpServletResponse response) throws Exception {

    DownloadForm result = new DownloadForm();

    if (file != null && StringUtils.isNotBlank(title) && CollectionUtils.isNotEmpty(pagesList)
            && CollectionUtils.isNotEmpty(textsList) && response != null) {

        final String originalName = file.getOriginalFilename();
        final String inputUri = this.fileUtils.saveFile(file);
        final String outputUri = this.fileUtils.getAutogeneratedName(originalName);

        // File is bookmarked
        try {// w  w w .  j  av  a  2  s  . c o  m
            final List<PDFGalBookmark> pdfGalBookmarksList = createPDFGalBookmarksList(pagesList, textsList);
            this.pdfGal.addBookmarks(inputUri, outputUri, title, pdfGalBookmarksList);
        } catch (COSVisitorException | IOException e) {
            // Temporal files are deleted from system
            this.fileUtils.delete(inputUri);
            this.fileUtils.delete(outputUri);
            throw e;
        }

        // Temporal files are deleted from system
        this.fileUtils.delete(inputUri);

        result = new DownloadForm(outputUri, originalName);
    }

    return result;
}

From source file:com.i10n.fleet.web.controllers.DriverAdminOperations.java

@SuppressWarnings("rawtypes")
public boolean Uploading(HttpServletRequest request) throws FileUploadException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        LOG.debug("File Not Uploaded");
    } else {/*from  w  w  w.  ja v a2s  . c o  m*/
        Iterator fileNames = null;
        fileNames = ((MultipartHttpServletRequest) request).getFileNames();
        MultipartFile file = null;
        if (fileNames.hasNext()) {
            String fileName = (String) fileNames.next();
            file = ((MultipartHttpServletRequest) request).getFile(fileName);
            String itemName = null;
            try {
                itemName = file.getOriginalFilename();
            } catch (Exception e) {
                LOG.error(e);
            }

            Random generator = new Random();
            int r = Math.abs(generator.nextInt());

            String reg = "[.*]";
            String replacingtext = "";

            Pattern pattern = Pattern.compile(reg);
            Matcher matcher = pattern.matcher(itemName);
            StringBuffer buffer = new StringBuffer();

            while (matcher.find()) {
                matcher.appendReplacement(buffer, replacingtext);
            }
            int IndexOf = itemName.indexOf(".");
            String domainName = itemName.substring(IndexOf);

            finalimage = buffer.toString() + "_" + r + domainName;
            savedFile = new File("/usr/local/tomcat6/webapps/driverimage/" + finalimage);
            savedFile.getAbsolutePath();
            try {
                file.transferTo(savedFile);
                /* *
                 * transferTo uses the tranfering a file location to destination
                 * 
                 */
            } catch (IllegalStateException e1) {
                LOG.error(e1);
            } catch (IOException e1) {
                LOG.error(e1);
            }
        }
    }
    return true;
}

From source file:fr.univrouen.poste.web.membre.PosteAPourvoirController.java

@RequestMapping(value = "/{id}/addFile", method = RequestMethod.POST, produces = "text/html")
@PreAuthorize("hasPermission(#id, 'manageposte')")
public String addFile(@PathVariable("id") Long id, @Valid PosteAPourvoirFile posteFile,
        BindingResult bindingResult, Model uiModel, HttpServletRequest request) throws IOException {
    if (bindingResult.hasErrors()) {
        logger.warn(bindingResult.getAllErrors());
        return "redirect:/posteapourvoirs/" + id.toString();
    }/*from  w w  w . j a  va 2s .  co m*/
    uiModel.asMap().clear();

    PosteAPourvoir poste = PosteAPourvoir.findPosteAPourvoir(id);

    // upload file
    MultipartFile file = posteFile.getFile();

    // sometimes file is null here, but I don't know how to reproduce this issue ... maybe that can occur only with some specifics browsers ?
    if (file != null) {
        String filename = file.getOriginalFilename();

        boolean filenameAlreadyUsed = false;
        for (PosteAPourvoirFile pcFile : poste.getPosteFiles()) {
            if (pcFile.getFilename().equals(filename)) {
                filenameAlreadyUsed = true;
                break;
            }
        }

        if (filenameAlreadyUsed) {
            uiModel.addAttribute("filename_already_used", filename);
            logger.warn("Upload Restriction sur '" + filename
                    + "' un fichier de mme nom existe dj pour le poste " + poste.getNumEmploi());
        } else {

            Long fileSize = file.getSize();

            if (fileSize != 0) {
                String contentType = file.getContentType();
                // cf https://github.com/EsupPortail/esup-dematec/issues/8 - workaround pour viter mimetype erron comme application/text-plain:formatted
                contentType = contentType.replaceAll(":.*", "");

                logger.info("Try to upload file '" + filename + "' with size=" + fileSize + " and contentType="
                        + contentType);

                InputStream inputStream = file.getInputStream();
                //byte[] bytes = IOUtils.toByteArray(inputStream);

                posteFile.setFilename(filename);
                posteFile.setFileSize(fileSize);
                posteFile.setContentType(contentType);
                logger.info("Upload and set file in DB with filesize = " + fileSize);
                posteFile.getBigFile().setBinaryFileStream(inputStream, fileSize);
                posteFile.getBigFile().persist();

                Calendar cal = Calendar.getInstance();
                Date currentTime = cal.getTime();
                posteFile.setSendTime(currentTime);

                poste.getPosteFiles().add(posteFile);
                poste.persist();

                logService.logActionPosteFile(LogService.UPLOAD_ACTION, poste, posteFile, request, currentTime);
            }
        }
    } else {
        String userId = SecurityContextHolder.getContext().getAuthentication().getName();
        String ip = request.getRemoteAddr();
        String userAgent = request.getHeader("User-Agent");
        logger.warn(userId + "[" + ip + "] tried to add a 'null file' ... his userAgent is : " + userAgent);
    }

    return "redirect:/posteapourvoirs/" + id.toString();
}

From source file:com.portal.controller.AdminController.java

@RequestMapping(value = "/employes/create", method = RequestMethod.POST)
public String submitCreateEmployee(HttpServletRequest request,
        @ModelAttribute("employeedto") EmployeeDTO employeedto,
        @RequestParam(value = "avatarFile", required = false) MultipartFile avatar) throws Exception {

    Employee employee = new Employee();

    if (!avatar.isEmpty() && avatar.getContentType().equals("image/jpeg")) {
        portalService.saveFile(//w  ww .j a  v a2 s  .  co  m
                request.getServletContext().getRealPath("/template/img/") + "/" + avatar.getOriginalFilename(),
                avatar);
        employee.setAvatar(avatar.getOriginalFilename());
    }

    if (employeedto.getName() == null || employeedto.getName().trim().length() == 0
            || employeedto.getPosition() == 0 || employeedto.getDepartment() == 0) {
        return "redirect:/admin/employes";
    }

    employee.setName(employeedto.getName());
    employee.setDepartment(portalService.getDepartment(employeedto.getDepartment()));
    employee.setPosition(portalService.getPosition(employeedto.getPosition()));
    employee.setPhone(employeedto.getPhone());
    employee.setEmail(employeedto.getEmail());
    employee.setDescription(employeedto.getDescription());

    portalService.saveEmployee(employee);
    return "redirect:/admin/employes";
}

From source file:org.grails.plugin.google.drive.GoogleDrive.java

public File uploadFile(MultipartFile multipartFile, String rootFolderName) throws IOException {
    String folderId = rootFolderName != null ? getFolderId(drive, rootFolderName) : null;

    if (folderId == null)
        folderId = insertFolder(drive, rootFolderName).getId();

    File fileMetadata = new File();
    fileMetadata.setTitle(multipartFile.getOriginalFilename());
    fileMetadata.setDescription(multipartFile.getOriginalFilename());
    fileMetadata.setMimeType(multipartFile.getContentType());

    // Set the parent folder.
    if (folderId != null)
        fileMetadata.setParents(Arrays.asList(new ParentReference().setId(folderId)));

    return insertFile(drive, fileMetadata, null, multipartFile);
}

From source file:org.sakaiproject.mailsender.tool.beans.EmailBean.java

public String sendEmail() {
    // make sure we have a minimum of data required
    if (emailEntry == null || emailEntry.getConfig() == null) {
        messages.addMessage(new TargettedMessage("error.nothing.send"));
        return EMAIL_FAILED;
    }/*w  ww.  ja va2  s .  c  om*/

    ConfigEntry config = emailEntry.getConfig();
    User curUser = externalLogic.getCurrentUser();

    String fromEmail = "";
    String fromDisplay = "";
    if (curUser != null) {
        fromEmail = curUser.getEmail();
        fromDisplay = curUser.getDisplayName();
    }

    if (fromEmail == null || fromEmail.trim().length() == 0) {
        messages.addMessage(new TargettedMessage("no.from.address"));
        return EMAIL_FAILED;
    }

    HashMap<String, String> emailusers = new HashMap<String, String>();

    // compile the list of emails to send to
    compileEmailList(fromEmail, emailusers);

    // handle the other recipients
    List<String> emailOthers = emailEntry.getOtherRecipients();
    String[] allowedDomains = StringUtil.split(configService.getString("sakai.mailsender.other.domains"), ",");

    List<String> invalids = new ArrayList<String>();
    // add other recipients to the message
    for (String email : emailOthers) {
        if (allowedDomains != null && allowedDomains.length > 0) {
            // check each "other" email to ensure it ends with an accepts domain
            for (String domain : allowedDomains) {
                if (email.endsWith(domain)) {
                    emailusers.put(email, null);
                } else {
                    invalids.add(email);
                }
            }
        } else {
            emailusers.put(email, null);
        }
    }

    String content = emailEntry.getContent();

    if (emailEntry.getConfig().isAppendRecipientList()) {
        content = content + compileRecipientList(emailusers);
    }

    String subjectContent = emailEntry.getSubject();
    if (subjectContent == null || subjectContent.trim().length() == 0) {
        subjectContent = messageLocator.getMessage("no.subject");
    }

    String subject = ((config.getSubjectPrefix() != null) ? config.getSubjectPrefix() : "") + subjectContent;

    try {
        if (invalids.size() == 0) {
            List<Attachment> attachments = new ArrayList<Attachment>();
            if (multipartMap != null && !multipartMap.isEmpty()) {
                for (Entry<String, MultipartFile> entry : multipartMap.entrySet()) {
                    MultipartFile mf = entry.getValue();
                    String filename = mf.getOriginalFilename();
                    try {
                        File f = File.createTempFile(filename, null);
                        mf.transferTo(f);
                        Attachment attachment = new Attachment(f, filename);
                        attachments.add(attachment);
                    } catch (IOException ioe) {
                        throw new AttachmentException(ioe.getMessage());
                    }
                }
            }
            // send the message
            invalids = externalLogic.sendEmail(config, fromEmail, fromDisplay, emailusers, subject, content,
                    attachments);
        }

        // append to the email archive
        String siteId = externalLogic.getSiteID();
        String fromString = fromDisplay + " <" + fromEmail + ">";
        addToArchive(config, fromString, subject, siteId);

        // build output message for results screen
        for (Entry<String, String> entry : emailusers.entrySet()) {
            String compareAddr = null;
            String addrStr = null;
            if (entry.getValue() != null && entry.getValue().trim().length() > 0) {
                addrStr = entry.getValue();
                compareAddr = "\"" + entry.getValue() + "\" <" + entry.getKey() + ">";
            } else {
                addrStr = entry.getKey();
                compareAddr = entry.getKey();
            }
            if (!invalids.contains(compareAddr)) {
                messages.addMessage(new TargettedMessage("verbatim", new String[] { addrStr },
                        TargettedMessage.SEVERITY_CONFIRM));
            }
        }
    } catch (MailsenderException me) {
        //Print this exception
        log.warn(me);
        messages.clear();
        List<Map<String, Object[]>> msgs = me.getMessages();
        if (msgs != null) {
            for (Map<String, Object[]> msg : msgs) {
                for (Map.Entry<String, Object[]> e : msg.entrySet()) {
                    messages.addMessage(
                            new TargettedMessage(e.getKey(), e.getValue(), TargettedMessage.SEVERITY_ERROR));
                }
            }
        } else {
            messages.addMessage(new TargettedMessage("verbatim", new String[] { me.getMessage() },
                    TargettedMessage.SEVERITY_ERROR));
        }
        return EMAIL_FAILED;
    } catch (AttachmentException ae) {
        messages.clear();
        messages.addMessage(new TargettedMessage("error.attachment", new String[] { ae.getMessage() },
                TargettedMessage.SEVERITY_ERROR));
        return EMAIL_FAILED;
    }

    // Display Users with Bad Emails if the option is turned on.
    boolean showBadEmails = config.isDisplayInvalidEmails();
    if (showBadEmails && invalids != null && invalids.size() > 0) {
        // add the message for the result screen
        String names = invalids.toString();
        messages.addMessage(new TargettedMessage("invalid.email.addresses",
                new String[] { names.substring(1, names.length() - 1) }, TargettedMessage.SEVERITY_INFO));
    }

    return EMAIL_SENT;
}

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

/**
 * *************************************************
 * URL: /appel-offre/file/upload upload(): receives files
 *
 * @param request : MultipartHttpServletRequest auto passed
 * @param response : HttpServletResponse auto passed
 * @param idAppelOffre/*from w w w .  j a va 2 s  .co m*/
 * @return LinkedList<FileMeta> as json format
 * **************************************************
 */
@RequestMapping(value = "/{idAppelOffre}/upload", method = RequestMethod.POST, produces = {
        MediaType.APPLICATION_JSON_VALUE })
public @ResponseBody LinkedList<FileMeta> upload(MultipartHttpServletRequest request,
        HttpServletResponse response, @PathVariable String idAppelOffre) {

    //1. build an iterator
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf = null;
    AppelOffre appelOffre = appelOffreService.findOne(Long.valueOf(idAppelOffre));
    int i = 0;
    //2. get each file
    while (itr.hasNext()) {
        System.out.println("i = " + i);
        //2.1 get next MultipartFile
        mpf = request.getFile(itr.next());

        System.out.println(mpf.getOriginalFilename() + " uploaded! ");

        //2.2 if files > 10 remove the first from the list
        //             if(files.size() >= 10)
        //                 files.pop();
        //2.3 create new fileMeta
        //             fileMeta = new FileMeta();
        //             fileMeta.setFileName(saveName);
        //             fileMeta.setFileSize(mpf.getSize()/1024+" Kb");
        //             fileMeta.setFileType(mpf.getContentType());
        try {
            //fileMeta.setBytes(mpf.getBytes());

            // copy file to local disk (make sure the path "e.g. D:/temp/files" exists)            
            String saveName = getFileName(mpf, appelOffre);
            processFileData(mpf, SAVE_DIRECTORY, saveName);
            //FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream("/home/gervais/" + saveName));
            appelOffre.addFile(saveName);
            appelOffre = appelOffreService.updateFiles(appelOffre);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //2.4 add to files
        // files.add(fileMeta);
    }
    // result will be like this
    // [{"fileName":"app_engine-85x77.png","fileSize":"8 Kb","fileType":"image/png"},...]
    files = new LinkedList<>();
    for (String file : appelOffre.getFiles()) {
        fileMeta = new FileMeta();
        fileMeta.setFileName(file);
        files.add(fileMeta);
    }
    return files;
}

From source file:org.kemri.wellcome.controller.ReportDefinitionController.java

@RequestMapping(value = Views.UPLOAD, method = RequestMethod.POST)
public @ResponseBody Map<String, ? extends Object> upload(@RequestParam("file") MultipartFile file, Model model)
        throws IOException {
    InputStream is = file.getInputStream();
    try {/*  ww w  . j av  a2s .c  o m*/
        service.unMarshallandSaveReportTemplates(is);
    } catch (Exception ex) {
        log.error(ex.getMessage());
        ex.printStackTrace();
    } finally {
        is.close();
    }
    log.info("User:" + service.getUsername() + " uploaded the report template :" + file.getOriginalFilename()
            + " on " + Calendar.getInstance().getTime());
    return Collections.singletonMap("u", "Saved");
}