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:net.shopxx.controller.admin.ThemeController.java

@RequestMapping(value = "/setting", method = RequestMethod.POST)
public String setting(String id, MultipartFile themeFile, RedirectAttributes redirectAttributes) {
    if (themeFile != null && !themeFile.isEmpty()) {
        if (!FilenameUtils.isExtension(themeFile.getOriginalFilename(), "zip")) {
            addFlashMessage(redirectAttributes, Message.error("admin.upload.invalid"));
            return "redirect:setting.jhtml";
        }/*from   w  ww.  j  a v  a2 s . c  o  m*/
        if (!themeService.upload(themeFile)) {
            addFlashMessage(redirectAttributes, Message.error("admin.theme.uploadInvalid"));
            return "redirect:setting.jhtml";
        }
    }
    Theme theme = themeService.get(id);
    if (theme == null) {
        return ERROR_VIEW;
    }
    Setting setting = SystemUtils.getSetting();
    setting.setTheme(theme.getId());
    SystemUtils.setSetting(setting);
    cacheService.clear();
    addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
    return "redirect:setting.jhtml";
}

From source file:de.metas.ui.web.upload.ImageRestController.java

@PostMapping
public int uploadImage(@RequestParam("file") final MultipartFile file) throws IOException {
    userSession.assertLoggedIn();/*from ww  w.  j a  v a 2s.  c o  m*/

    final String name = file.getOriginalFilename();
    final byte[] data = file.getBytes();

    final MImage adImage = new MImage(userSession.getCtx(), 0, ITrx.TRXNAME_None);
    adImage.setName(name);
    adImage.setBinaryData(data);
    InterfaceWrapperHelper.save(adImage);

    return adImage.getAD_Image_ID();
}

From source file:net.oletalk.hellospringboot.controller.HelloController.java

@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes attributes) {
    // multipart file upload is slightly different

    String originalName = file.getOriginalFilename();
    // TODO any way of getting files uploaded without transferring to a temp file?
    //  It seems to want to know the complete path but MultipartFile doesn't give us that.
    String returnMsg;/*from   w ww.ja  v a  2s .co m*/
    try {
        LOG.info("Creating temp file for upload");
        File tmpFile = File.createTempFile("s3upload", null);
        tmpFile.deleteOnExit();
        file.transferTo(tmpFile);
        returnMsg = s3service.uploadDocument("test/" + originalName, tmpFile);
        attributes.addFlashAttribute("message", returnMsg);
    } catch (IOException ioe) {
        LOG.error("Error creating temp file for upload:" + ioe.toString());
        attributes.addFlashAttribute("message", "Problem preparing upload to S3");
    }
    return "redirect:/hello/doc/";
}

From source file:io.pivotal.PaasappApplication.java

@RequestMapping("upload")
public String uploadFiles(HttpServletRequest request) throws IllegalStateException, IOException {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
            request.getSession().getServletContext());
    if (multipartResolver.isMultipart(request)) {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        //?multiRequest ??
        Iterator iter = multiRequest.getFileNames();

        while (iter.hasNext()) {
            //??// w  w w  . j  a  v a  2 s  .c o  m
            MultipartFile file = multiRequest.getFile(iter.next().toString());
            if (file != null) {
                String path = file.getOriginalFilename();
                //
                file.transferTo(new File(path));
            }

        }
    }

    return "/success";
}

From source file:com.kalai.controller.FileUploadController.java

@RequestMapping(value = "/savefiles", method = RequestMethod.POST)
public String fileupload(@ModelAttribute("uploadForm") filesupload fileup, Model map)
        throws IllegalStateException, IOException {
    String saveDirectory = "D:/spring_file_upload/";
    List<MultipartFile> files = fileup.getFiles();
    List<String> filenames = new ArrayList<String>();
    try {//  www. j a v  a2 s.c o  m
        if (null != files && !files.isEmpty()) {
            for (MultipartFile multipartfile : files) {
                String fileName = multipartfile.getOriginalFilename();
                if (!"".equalsIgnoreCase(fileName)) {
                    multipartfile.transferTo(new File(saveDirectory + fileName));
                    filenames.add(fileName);
                }
            }
            map.addAttribute("uploadoption", "uploaded");
            map.addAttribute("files", filenames);
        } else {
            map.addAttribute("uploadoption", "emptyfiles");
            map.addAttribute("files", filenames);
        }

    } catch (Exception e) {
        return e.getMessage();
    }
    return "fileupload";
}

From source file:pt.ist.fenix.ui.spring.PagesAdminController.java

@RequestMapping(value = "/attachment/{menuItemId}", method = RequestMethod.POST)
public @ResponseBody String addAttachments(@PathVariable("menuItemId") String menuItemId,
        @RequestParam("file") MultipartFile file) throws IOException {
    service.addAttachment(file.getOriginalFilename(), file, getDomainObject(menuItemId));
    return getAttachments(menuItemId);
}

From source file:com.seer.datacruncher.spring.ValidateFilePopupController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String idSchema = request.getParameter("idSchema");
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("file");
    String resMsg = "";

    if (multipartFile.getOriginalFilename().endsWith(FileExtensionType.ZIP.getAbbreviation())) {
        // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one      
        ZipInputStream inStream = null;
        try {/*from  w w  w  . j  ava  2s.  c om*/
            inStream = new ZipInputStream(multipartFile.getInputStream());
            ZipEntry entry;
            while (!(isStreamClose(inStream)) && (entry = inStream.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    DatastreamsInput datastreamsInput = new DatastreamsInput();
                    datastreamsInput.setUploadedFileName(entry.getName());
                    byte[] byteInput = IOUtils.toByteArray(inStream);
                    resMsg += datastreamsInput.datastreamsInput(new String(byteInput), Long.parseLong(idSchema),
                            byteInput);
                }
                inStream.closeEntry();
            }
        } catch (IOException ex) {
            resMsg = "Error occured during fetch records from ZIP file.";
        } finally {
            if (inStream != null)
                inStream.close();
        }
    } else {
        // Case 1: When user upload a single file. In this cae just validate a single stream 
        String datastream = new String(multipartFile.getBytes());
        DatastreamsInput datastreamsInput = new DatastreamsInput();
        datastreamsInput.setUploadedFileName(multipartFile.getOriginalFilename());

        resMsg = datastreamsInput.datastreamsInput(datastream, Long.parseLong(idSchema),
                multipartFile.getBytes());

    }
    String msg = resMsg.replaceAll("'", "\"").replaceAll("\\n", " ");
    msg = msg.trim();
    response.setContentType("text/html");
    ServletOutputStream out = null;
    out = response.getOutputStream();
    out.write(("{success: " + true + " , message:'" + msg + "',   " + "}").getBytes());
    out.flush();
    out.close();
    return null;
}

From source file:com.qq.tars.web.controller.patch.UploadController.java

@RequestMapping(value = "server/api/upload_patch_package", produces = "application/json")
@ResponseBody//from www  .j  av a  2s . com
public ServerPatchView upload(@Application @RequestParam String application,
        @ServerName @RequestParam("module_name") String moduleName, HttpServletRequest request,
        ModelMap modelMap) throws Exception {
    String comment = StringUtils.trimToEmpty(request.getParameter("comment"));
    String uploadTgzBasePath = systemConfigService.getUploadTgzPath();

    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
            request.getSession().getServletContext());
    if (multipartResolver.isMultipart(request)) {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        Iterator<String> it = multiRequest.getFileNames();
        if (it.hasNext()) {
            MultipartFile file = multiRequest.getFile(it.next());

            String originalName = file.getOriginalFilename();
            String extension = FilenameUtils.getExtension(originalName);
            String temporary = uploadTgzBasePath + "/" + UUID.randomUUID() + "." + extension;
            IOUtils.copy(file.getInputStream(), new FileOutputStream(temporary));

            String packageType = "suse";

            // war?
            if (temporary.endsWith(".war")) {
                temporary = patchService.war2tgz(temporary, moduleName);
            }

            // ?
            String updateTgzPath = uploadTgzBasePath + "/" + application + "/" + moduleName;

            // ????
            String uploadTgzName = application + "." + moduleName + "_" + packageType + "_"
                    + System.currentTimeMillis() + ".tgz";

            // ??
            String uploadTgzFullPath = updateTgzPath + "/" + uploadTgzName;

            log.info("temporary path={}, upload path={}", temporary, uploadTgzFullPath);

            File uploadPathDir = new File(updateTgzPath);
            if (!uploadPathDir.exists()) {
                if (!uploadPathDir.mkdirs()) {
                    throw new IOException(
                            String.format("mkdirs error, path=%s", uploadPathDir.getCanonicalPath()));
                }
            }

            FileUtils.moveFile(new File(temporary), new File(uploadTgzFullPath));

            return mapper.map(patchService.addServerPatch(application, moduleName, uploadTgzFullPath, comment),
                    ServerPatchView.class);
        }
    }

    throw new Exception("???");
}

From source file:org.sakaiproject.imagegallery.integration.sakai.FileLibraryLegacyResources.java

public ImageFile storeImageFile(MultipartFile sourceImageFile) {
    String filename = sourceImageFile.getOriginalFilename();
    String collectionId = getSiteCollectionId(galleryCollectionName);
    try {/*from   w  ww .j av a2 s.  com*/
        ContentResourceEdit resource = contentHostingService.addResource(collectionId,
                FilenameUtils.getBaseName(filename), FilenameUtils.getExtension(filename), 500);
        resource.setContentType(sourceImageFile.getContentType());
        resource.setContent(sourceImageFile.getInputStream());
        contentHostingService.commitResource(resource);
        return mapResourceToImageFile(resource);
    } catch (PermissionException e) {
        throw new RuntimeException(e);
    } catch (IdUniquenessException e) {
        throw new RuntimeException(e);
    } catch (IdLengthException e) {
        throw new RuntimeException(e);
    } catch (IdInvalidException e) {
        throw new RuntimeException(e);
    } catch (IdUnusedException e) {
        throw new RuntimeException(e);
    } catch (OverQuotaException e) {
        throw new RuntimeException(e);
    } catch (ServerOverloadException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.example.securelogin.app.common.validation.FileExtensionValidator.java

@Override
public boolean isValid(MultipartFile value, ConstraintValidatorContext context) {
    if (value == null) {
        return true;
    }//from ww w  .  j a v a  2s .  c  o  m

    String fileNameExtension = StringUtils.getFilenameExtension(value.getOriginalFilename());
    if (!StringUtils.hasLength(fileNameExtension)) {
        return false;
    }

    for (String extension : extensions) {
        if (fileNameExtension.equals(extension)
                || ignoreCase && fileNameExtension.equalsIgnoreCase(extension)) {
            return true;
        }
    }
    return false;
}