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

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

Introduction

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

Prototype

String getName();

Source Link

Document

Return the name of the parameter in the multipart form.

Usage

From source file:eu.freme.eservices.publishing.ServiceRestController.java

@RequestMapping(value = "/e-publishing/html", method = RequestMethod.POST)
public ResponseEntity<byte[]> htmlToEPub(@RequestParam("htmlZip") MultipartFile file,
        @RequestParam("metadata") String jMetadata)
        throws IOException, InvalidZipException, EPubCreationException, MissingMetadataException {
    Gson gson = new Gson();
    Metadata metadata = gson.fromJson(jMetadata, Metadata.class);
    MultiValueMap<String, String> headers = new HttpHeaders();
    headers.add(HttpHeaders.CONTENT_TYPE, "Application/epub+zip");
    String filename = file.getName();
    headers.add(HttpHeaders.CONTENT_DISPOSITION, "Attachment; filename=" + filename.split("\\.")[0] + ".epub");
    try (InputStream in = file.getInputStream()) {
        return new ResponseEntity<>(epubAPI.createEPUB(metadata, in), headers, HttpStatus.OK);
    }//  w ww  .j  av a 2s . com
}

From source file:fr.mby.opa.pics.web.controller.UploadPicturesController.java

protected List<Path> processArchive(final MultipartFile multipartFile) throws IOException {
    final List<Path> archivePictures = new ArrayList<>(128);

    // We copy the archive in a tmp file
    final File tmpFile = File.createTempFile(multipartFile.getName(), ".tmp");
    multipartFile.transferTo(tmpFile);//from  w  w  w. java 2 s . co  m
    // final InputStream archiveInputStream = multipartFile.getInputStream();
    // Streams.copy(archiveInputStream, new FileOutputStream(tmpFile), true);
    // archiveInputStream.close();

    final Path tmpFilePath = tmpFile.toPath();
    final FileSystem archiveFs = FileSystems.newFileSystem(tmpFilePath, null);

    final Iterable<Path> rootDirs = archiveFs.getRootDirectories();
    for (final Path rootDir : rootDirs) {
        Files.walkFileTree(rootDir, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(final Path path, final BasicFileAttributes attrs)
                    throws IOException {
                final boolean isDirectory = Files.isDirectory(path);

                if (!isDirectory) {
                    final String contentType = Files.probeContentType(path);
                    if (contentType != null && contentType.startsWith("image/")) {
                        archivePictures.add(path);
                    }
                }

                return super.visitFile(path, attrs);
            }
        });
    }

    return archivePictures;
}

From source file:com.ar.dev.tierra.api.controller.UsuariosController.java

@RequestMapping(value = "/updatePhoto", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<?> updateUsuario(@RequestParam("file") MultipartFile file,
        OAuth2Authentication authentication) {
    try {//from   w w w .j  a  va  2 s  .com
        User user = (User) authentication.getPrincipal();
        Usuarios u = facadeService.getUsuariosDAO().findUsuarioByUsername(user.getUsername());
        if (file.getName().isEmpty() == false) {
            InputStream inputStream = file.getInputStream();
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            int nRead;
            byte[] bytes = new byte[16384];
            while ((nRead = inputStream.read(bytes, 0, bytes.length)) != -1) {
                buffer.write(bytes, 0, nRead);
            }
            buffer.flush();
            u.setImagen(buffer.toByteArray());
            facadeService.getUsuariosDAO().updateUsuario(u);
        }
    } catch (Exception e) {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }
    return new ResponseEntity<>(HttpStatus.OK);
}

From source file:wad.controller.ReceiptController.java

@RequestMapping(method = RequestMethod.POST)
public String addReceipt(@RequestParam("file") MultipartFile file, @PathVariable Long expenseId,
        @ModelAttribute Receipt receipt, BindingResult bindingResult, @ModelAttribute Expense expense,
        SessionStatus status, RedirectAttributes redirectAttrs) throws IOException {

    if (expense == null || !expense.isEditableBy(userService.getCurrentUser())) {
        throw new ResourceNotFoundException();
    }//  ww w.  j  a  v  a2 s.  co  m

    receipt.setName(file.getName());
    receipt.setMediaType(file.getContentType());
    receipt.setSize(file.getSize());
    receipt.setContent(file.getBytes());
    receipt.setSubmitted(new Date());
    receipt.setExpense(expense);

    receiptValidator.validate(receipt, bindingResult);

    if (bindingResult.hasErrors()) {
        redirectAttrs.addFlashAttribute("errors", bindingResult.getAllErrors());
        return "redirect:/expenses/" + expense.getId();
    }

    receiptRepository.save(receipt);

    status.setComplete();

    return "redirect:/expenses/" + expense.getId();
}

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

private void addToArchive(ConfigEntry config, String fromString, String subject, String siteId) {
    if (emailEntry.getConfig().isAddToArchive()) {
        StringBuilder attachment_info = new StringBuilder("<br/>");
        int i = 1;
        for (MultipartFile file : multipartMap.values()) {
            if (file.getSize() > 0) {
                attachment_info.append("<br/>");
                attachment_info.append("Attachment #").append(i).append(": ").append(file.getName()).append("(")
                        .append(file.getSize()).append(" Bytes)");
                i++;/*from ww w .  ja v a 2  s .co m*/
            }
        }
        String emailarchive = "/mailarchive/channel/" + siteId + "/main";
        String content = emailEntry.getContent() + attachment_info.toString();
        externalLogic.addToArchive(config, emailarchive, fromString, subject, content);
    }
}

From source file:com.baidu.gcrm.materials.web.MaterialsAction.java

/**
 * //from   w  ww.  ja  v  a  2 s .c om
 * 
 * @return
 */
@RequestMapping("/doUploadFile")
@ResponseBody
public Object doUploadFile(MultipartHttpServletRequest multipartRequest, HttpServletResponse response) {
    Iterator<String> it = multipartRequest.getFileNames();
    MultipartFile mpf = null;
    while (it.hasNext()) {
        String fileName = it.next();
        mpf = multipartRequest.getFile(fileName);
        log.debug("===" + fileName + "upload to local sever");
    }

    //
    Attachment attachment = new Attachment();
    attachment.setFieldName(mpf.getName());
    attachment.setName(mpf.getOriginalFilename());
    attachment.setCustomerNumber(-1L);
    attachment.setId(-1L);
    attachment.setTempUrl("");
    //attachment.setType(-1);
    attachment.setUrl("");
    //   attachment.setExit(false);
    try {
        attachment.setBytes(mpf.getBytes());
    } catch (IOException e) {
        log.error("=====" + e.getMessage());
        attachment.setMessage("failed");
        return attachment;
    }

    if (!StringUtils.isEmpty(mpf.getOriginalFilename())) {
        if (mpf.getOriginalFilename().endsWith(".exe")) {
            attachment.setMessage("materials.extension.error");//I18N?code
        } else {
            if (matericalsService.uploadFile(attachment)) {
                attachment.setMessage("success");
            } else {
                attachment.setMessage("failed");
            }
        }
    }

    //?
    String userAgent = multipartRequest.getHeader("user-agent").toLowerCase();
    if (userAgent.indexOf("msie 6") != -1 || userAgent.indexOf("msie 7") != -1
            || userAgent.indexOf("msie 8") != -1 || userAgent.indexOf("msie 9") != -1) {
        return JSONObject.toJSONString(attachment);

    }
    return attachment;
}

From source file:com.cloudbees.demo.beesshop.web.ProductController.java

/**
 * @param id    id of the product/* www.  j  ava 2  s .c om*/
 * @param photo to associate with the product
 * @return redirection to display product
 */
@RequestMapping(value = "/product/{id}/photo", method = RequestMethod.POST)
@Transactional
public String updatePhoto(@PathVariable long id, @RequestParam("photo") MultipartFile photo) {

    if (photo.getSize() == 0) {
        logger.info("Empty uploaded file");
    } else {
        try {
            String contentType = fileStorageService.findContentType(photo.getOriginalFilename());
            if (contentType == null) {
                logger.warn("Skip file with unsupported extension '{}'", photo.getName());
            } else {

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

                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(photoInputStream, objectMetadata);

                Product product = productRepository.get(id);
                logger.info("Saved {}", photoUrl);
                product.setPhotoUrl(photoUrl);
                productRepository.update(product);
            }

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

From source file:com.abixen.platform.core.service.impl.LayoutServiceImpl.java

@Override
public Layout changeIcon(Long id, MultipartFile iconFile) throws IOException {
    Layout layout = findLayout(id);//w  w  w. ja  v  a  2 s .com
    File currentAvatarFile = new File(platformResourceConfigurationProperties.getImageLibraryDirectory()
            + "/layout-miniature/" + layout.getIconFileName());
    if (currentAvatarFile.exists()) {
        if (!currentAvatarFile.delete()) {
            throw new FileExistsException();
        }
    }
    PasswordEncoder encoder = new BCryptPasswordEncoder();
    String newIconFileName = encoder.encode(iconFile.getName() + new Date().getTime()).replaceAll("\"", "s")
            .replaceAll("/", "a").replace(".", "sde");
    File newIconFile = new File(platformResourceConfigurationProperties.getImageLibraryDirectory()
            + "/layout-miniature/" + newIconFileName);
    FileOutputStream out = new FileOutputStream(newIconFile);
    out.write(iconFile.getBytes());
    out.close();
    layout.setIconFileName(newIconFileName);
    updateLayout(layout);
    return findLayout(id);
}

From source file:cz.zcu.kiv.eegdatabase.webservices.rest.scenario.ScenarioServiceController.java

/**
 * Creates new scenario record.//from   w  w w . ja va2  s .c o  m
 *
 * @param request         HTTP request
 * @param response        HTTP response
 * @param scenarioName    scenario name
 * @param researchGroupId research group to which should be new record assigned
 * @param mimeType        scenario file MIME type
 * @param isPrivate       is scenario private
 * @param description     scenario description
 * @param file            file content
 * @return filled scenario data container
 * @throws RestServiceException error while creating new scenario record
 */
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public ScenarioData create(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("scenarioName") String scenarioName, @RequestParam("researchGroupId") int researchGroupId,
        @RequestParam(value = "mimeType", required = false) String mimeType,
        @RequestParam(value = "private", required = false) boolean isPrivate,
        @RequestParam("description") String description, @RequestParam("file") MultipartFile file)
        throws RestServiceException {
    ScenarioData scenarioData = new ScenarioData();
    scenarioData.setScenarioName(scenarioName);
    scenarioData.setResearchGroupId(researchGroupId);
    scenarioData.setDescription(description);
    scenarioData.setMimeType(mimeType != null ? mimeType : file.getContentType());
    scenarioData.setPrivate(isPrivate);
    scenarioData.setFileName(file.getName());
    scenarioData.setFileLength((int) file.getSize());

    try {
        int pk = scenarioService.create(scenarioData, file);
        scenarioData.setScenarioId(pk);

        Person user = personDao.getLoggedPerson();
        scenarioData.setOwnerName(user.getGivenname() + " " + user.getSurname());
        ResearchGroup group = researchGroupDao.read(scenarioData.getResearchGroupId());
        scenarioData.setResearchGroupName(group.getTitle());

        response.addHeader("Location", buildLocation(request, pk));
        return scenarioData;
    } catch (IOException e) {
        log.error(e);
        throw new RestServiceException(e);
    } catch (SAXException e) {
        log.error(e);
        throw new RestServiceException(e);
    } catch (ParserConfigurationException e) {
        log.error(e);
        throw new RestServiceException(e);
    }
}

From source file:com.pantuo.service.impl.AttachmentServiceImpl.java

@Override
public String savePayvoucher(HttpServletRequest request, String user_id, int main_id,
        JpaAttachment.Type file_type, String description) throws BusinessException {
    String result = "";
    try {/*from ww  w  .j  av a  2 s . co m*/
        CustomMultipartResolver multipartResolver = new CustomMultipartResolver(
                request.getSession().getServletContext());
        log.info("userid:{},main_id:{},file_type:{}", user_id, main_id, file_type);
        if (multipartResolver.isMultipart(request)) {
            String path = request.getSession().getServletContext()
                    .getRealPath(com.pantuo.util.Constants.FILE_UPLOAD_DIR).replaceAll("WEB-INF", "");
            log.info("path=", path);
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile(iter.next());
                if (file != null && !file.isEmpty()) {
                    String oriFileName = file.getOriginalFilename();
                    String fn = file.getName();
                    if (StringUtils.isNoneBlank(oriFileName)) {

                        String storeName = GlobalMethods
                                .md5Encrypted((System.currentTimeMillis() + oriFileName).getBytes());
                        Pair<String, String> p = FileHelper.getUploadFileName(path,
                                storeName += FileHelper.getFileExtension(oriFileName, true));
                        File localFile = new File(p.getLeft());
                        file.transferTo(localFile);
                        AttachmentExample example = new AttachmentExample();
                        AttachmentExample.Criteria criteria = example.createCriteria();
                        criteria.andMainIdEqualTo(main_id);
                        criteria.andUserIdEqualTo(user_id);
                        criteria.andTypeEqualTo(JpaAttachment.Type.payvoucher.ordinal());
                        List<Attachment> attachments = attachmentMapper.selectByExample(example);
                        if (attachments.size() > 0) {
                            Attachment t = attachments.get(0);
                            t.setUpdated(new Date());
                            t.setName(oriFileName);
                            t.setUrl(p.getRight());
                            attachmentMapper.updateByPrimaryKey(t);
                            result = p.getRight();
                        } else {
                            Attachment t = new Attachment();
                            if (StringUtils.isNotBlank(description)) {
                                t.setDescription(description);
                            }
                            t.setMainId(main_id);
                            t.setType(file_type.ordinal());
                            t.setCreated(new Date());
                            t.setUpdated(t.getCreated());
                            t.setName(oriFileName);
                            t.setUrl(p.getRight());
                            t.setUserId(user_id);
                            attachmentMapper.insert(t);
                            result = p.getRight();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        log.error("saveAttachment", e);
        throw new BusinessException("saveAttachment-error", e);
    }
    return result;
}