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:no.dusken.aranea.admin.control.UploadFileController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object object,
        BindException bindException) throws Exception {

    String url = ServletRequestUtils.getRequiredStringParameter(request, "imageUrl");

    // get the uploaded file
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile file = multipartRequest.getFile("file");
    if (file == null) {
        // There is no file. Exit
        log.error("Could not extract file from request");
        return new ModelAndView(new EmptyView());
    }/*from w  w w. ja  v  a 2s  . co m*/
    // transfer the file to a temporary location
    String originalName = file.getOriginalFilename();
    log.debug("Got file: {}", originalName);
    File tmpFile = new File(resourceDir + "/images/tmp/" + originalName);
    tmpFile.getParentFile().mkdirs();
    file.transferTo(tmpFile);

    // move the file to the final destination
    File newFile = new File(resourceDir + "/images/" + url);
    newFile.getParentFile().mkdirs();
    FileUtils.moveFile(tmpFile, newFile);
    // SUCCESS!
    response.setStatus(200);

    return new ModelAndView(new EmptyView());
}

From source file:cherry.foundation.async.AsyncFileProcessHandlerImpl.java

/**
 * ?????/*from   w ww. j a  v  a  2 s  . c  om*/
 *
 * @param launcherId ?????ID
 * @param description 
 * @param file ??
 * @param handlerName ????????Bean?????Bean?{@link FileProcessHandler}???????
 * @param args 
 * @return ??????ID
 */
@Override
public long launchFileProcess(String launcherId, String description, MultipartFile file, String handlerName,
        String... args) {

    long asyncId = asyncProcessStore.createFileProcess(launcherId, bizDateTime.now(), description,
            file.getName(), file.getOriginalFilename(), file.getContentType(), file.getSize(), handlerName,
            args);
    try {

        File tempFile = createFile(file);

        Map<String, String> message = new HashMap<>();
        message.put(ASYNCID, String.valueOf(asyncId));
        message.put(FILE, tempFile.getAbsolutePath());
        message.put(NAME, file.getName());
        message.put(ORIGINAL_FILENAME, file.getOriginalFilename());
        message.put(CONTENT_TYPE, file.getContentType());
        message.put(SIZE, String.valueOf(file.getSize()));
        message.put(HANDLER_NAME, handlerName);
        for (int i = 0; i < args.length; i++) {
            message.put(String.valueOf(i), args[i]);
        }
        jmsOperations.convertAndSend(message, messagePostProcessor);

        asyncProcessStore.updateToLaunched(asyncId, bizDateTime.now());
        return asyncId;
    } catch (IOException ex) {
        asyncProcessStore.finishWithException(asyncId, bizDateTime.now(), ex);
        throw new IllegalStateException(ex);
    }
}

From source file:com.igame.app.controller.Image2Controller.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody Map upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    // HttpSession
    SecUser user = (SecUser) request.getSession().getAttribute("user");
    long appid = user.getAppid();
    log.debug("uploadPost called appid:{}" + appid);
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf;
    List<Image> list = new LinkedList<>();

    while (itr.hasNext()) {
        mpf = request.getFile(itr.next());
        log.debug("Uploading {}", mpf.getOriginalFilename());

        long id = IDGenerator.getKey();
        // String newFilenameBase = String.valueOf(id);
        String originalFileExtension = mpf.getOriginalFilename()
                .substring(mpf.getOriginalFilename().lastIndexOf("."));
        String newFilename = id + originalFileExtension;
        String storageDirectory = fileUploadDirectory;
        String contentType = mpf.getContentType();

        File newFile = new File(storageDirectory + "/" + "app-" + appid + "/" + newFilename);

        if (!newFile.getParentFile().exists()) {
            log.debug(" {}" + newFile.getParentFile().getPath());
            newFile.getParentFile().mkdirs();
        }/*from   ww  w.j a  v a2  s.  com*/

        try {
            mpf.transferTo(newFile);

            BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 150);
            String thumbnailFilename = id + "-thumbnail.png";
            File thumbnailFile = new File(storageDirectory + "/" + "app-" + appid + "/" + thumbnailFilename);
            ImageIO.write(thumbnail, "png", thumbnailFile);

            Image image = new Image();
            image.setId(id);
            image.setAppid(appid);
            image.setName(mpf.getOriginalFilename());
            image.setThumbnailFilename(thumbnailFilename);
            image.setNewFilename(newFilename);
            image.setContentType(contentType);
            image.setSize(mpf.getSize());
            image.setThumbnailSize(thumbnailFile.length());
            image = imageService.create(image);

            image.setUrl("app-" + appid + "/" + newFilename);
            image.setThumbnailUrl("app-" + appid + "/" + thumbnailFilename);
            image.setDeleteUrl("delete/" + image.getId());
            image.setDeleteType("DELETE");

            list.add(image);

        } catch (IOException e) {
            log.error("Could not upload file " + mpf.getOriginalFilename(), e);
        }

    }

    Map<String, Object> files = new HashMap<>();
    files.put("files", list);
    return files;
}

From source file:com.dpillay.projects.yafu.controller.FileUploadController.java

@RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)//from w w  w .j ava 2s.  c o  m
public String handleFormUpload(@RequestParam(value = "file", required = false) final MultipartFile file,
        @RequestParam(value = "key", required = false) final String key, ModelMap modelMap,
        final HttpServletRequest request) {
    if (log.isDebugEnabled())
        log.debug("Received upload file: {} with key: {}", file.getOriginalFilename(), key);
    if (!file.isEmpty()) {
        try {
            getFileUploadStatus(key, file, request.getSession().getId());
        } catch (IOException e) {
            log.error(e.getLocalizedMessage(), e);
        }
    }
    return null;
}

From source file:org.spirit.spring.handler.BotListAdminHandler.java

public BotListDocFileMetadata uploadCurFile(HttpServletRequest request, Object form, MultipartFile entity)
        throws IllegalStateException, IOException {

    String uploadDir = this.controller.getFileUploadUtil().getUploadDir();
    String filename = entity.getOriginalFilename();
    String uid = BotListUniqueId.getUniqueId();

    String newFilename = "doc" + uid + ".txt";

    File fileUpload = new File(uploadDir + "/" + newFilename);
    entity.transferTo(fileUpload);/*  w  w w . j  a  va 2  s.c om*/

    // Create the file metadata bean
    BotListDocFileMetadata metadata = new BotListDocFileMetadata();

    metadata.setDocFilesize(new Long(entity.getSize()));
    metadata.setDocFilename(newFilename);
    metadata.setDocOriginalname(filename);

    return metadata;

}

From source file:com.glaf.core.web.springmvc.MxUploadController.java

@RequestMapping("/uploadNow")
public ModelAndView upload(HttpServletRequest request, ModelMap modelMap) {
    LoginContext loginContext = RequestUtils.getLoginContext(request);

    MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
    String type = req.getParameter("type");
    if (StringUtils.isEmpty(type)) {
        type = "0";
    }// ww  w.  j  av a  2  s . c o m

    String serviceKey = req.getParameter("serviceKey");
    if (StringUtils.isEmpty(serviceKey)) {
        modelMap.put("error_message", "????serviceKey?");
        return new ModelAndView("/error");
    }

    Map<String, Object> paramMap = RequestUtils.getParameterMap(req);
    logger.debug("paramMap:" + paramMap);
    String businessKey = req.getParameter("businessKey");
    String objectId = req.getParameter("objectId");
    String objectValue = req.getParameter("objectValue");
    int status = ParamUtils.getInt(paramMap, "status");
    List<DataFile> dataFiles = new java.util.ArrayList<DataFile>();
    try {
        semaphore.acquire();

        if (StringUtils.isNotEmpty(businessKey)) {
            List<DataFile> rows = blobService.getBlobList(businessKey);
            if (rows != null && rows.size() > 0) {
                dataFiles.addAll(rows);
            }
        }

        paramMap.remove("businessKey");
        paramMap.put("createBy", loginContext.getActorId());
        paramMap.put("serviceKey", serviceKey);
        paramMap.put("status", status);
        BlobItemQuery query = new BlobItemQuery();
        Tools.populate(query, paramMap);

        query.createBy(loginContext.getActorId());
        query.serviceKey(serviceKey);
        query.status(status);
        List<DataFile> rows = blobService.getBlobList(query);
        if (rows != null && rows.size() > 0) {
            Iterator<DataFile> iterator = rows.iterator();
            while (iterator.hasNext()) {
                DataFile dataFile = iterator.next();
                if (!dataFiles.contains(dataFile)) {
                    dataFiles.add(dataFile);
                }
            }
        }

        Map<String, MultipartFile> fileMap = req.getFileMap();
        Set<Entry<String, MultipartFile>> entrySet = fileMap.entrySet();
        for (Entry<String, MultipartFile> entry : entrySet) {
            MultipartFile mFile = entry.getValue();
            if (mFile.getOriginalFilename() != null && mFile.getSize() > 0) {
                String filename = mFile.getOriginalFilename();
                logger.debug("upload file:" + filename);
                String fileId = UUID32.getUUID();
                if (filename.indexOf("/") != -1) {
                    filename = filename.substring(filename.lastIndexOf("/") + 1, filename.length());
                } else if (filename.indexOf("\\") != -1) {
                    filename = filename.substring(filename.lastIndexOf("\\") + 1, filename.length());
                }
                BlobItem dataFile = new BlobItemEntity();
                dataFile.setLastModified(System.currentTimeMillis());
                dataFile.setCreateBy(loginContext.getActorId());
                dataFile.setFileId(fileId);
                dataFile.setData(mFile.getBytes());
                dataFile.setFilename(filename);
                dataFile.setName(mFile.getName());
                dataFile.setContentType(mFile.getContentType());
                dataFile.setSize((int) mFile.getSize());
                dataFile.setType(type);
                dataFile.setStatus(status);
                dataFile.setObjectId(objectId);
                dataFile.setObjectValue(objectValue);
                dataFile.setServiceKey(serviceKey);
                blobService.insertBlob(dataFile);
                dataFile.setData(null);
                dataFiles.add(dataFile);
            }
        }

        if (dataFiles.size() > 0) {
            modelMap.put("dataFiles", dataFiles);
        }

    } catch (Exception ex) {
        logger.debug(ex);
        return new ModelAndView("/error");
    } finally {
        semaphore.release();
    }

    return this.showUpload(request, modelMap);
}

From source file:gerenciador.incubadora.controller.ArquivoController.java

@RequestMapping(value = "/imagem/upload/{id}", method = RequestMethod.POST)
public ModelAndView upload(@RequestParam("logo") MultipartFile file, @PathVariable Long id) throws IOException {
    ModelAndView mv;/*w  w w  . ja v a2s .  c o m*/
    try {
        byte[] bytes = file.getBytes();
        Empreendimento empreendimento = new Empreendimento();
        empreendimento.setId(id);

        String logo = "C://imagens//empreendimento//" + id + " - " + file.getOriginalFilename();

        empreendimento.setLogo(logo);
        ServiceLocator.getEmpreendimentoService().uplaod(bytes, empreendimento);
        empreendimento = ServiceLocator.getEmpreendimentoService().readById(id);
        mv = new ModelAndView("redirect:/empreendimento");
        mv.addObject("empreendimento", empreendimento);
    } catch (Exception ex) {
        mv = new ModelAndView("error");
        mv.addObject("e", ex);
    }
    return mv;
}

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

private boolean uploadable(MultipartFile file) {
    if (file.getSize() > Config.MAX_FILE_SIZE) {
        throw new IllegalArgumentException("5M??");
    }/*from w  ww.  j  ava2  s .c  o  m*/

    String fileName = file.getOriginalFilename();
    if (RegexUtils.uploadable(fileName)) {
        return true;
    }
    throw new IllegalArgumentException("???");
}

From source file:com.cisco.ca.cstg.pdi.controllers.license.LicenseController.java

@RequestMapping(value = "/licenseUpload.html", method = RequestMethod.POST)
public ModelAndView licenseUpload(@RequestParam("upload_license") MultipartFile file) {
    ModelAndView modelAndView = null;//from w w  w .  j a v a  2 s.c  o m

    if (file == null) {
        modelAndView = new ModelAndView(RESPONSE_LICENSE_UPLOAD, KEY_ERROR_MESSAGE, "The file is null.");
    } else {

        String fileName = file.getOriginalFilename();
        LOGGER.info("File Name is " + fileName);
        if ((fileName == null) || (fileName.trim().length() <= 0)) {
            modelAndView = new ModelAndView(RESPONSE_LICENSE_UPLOAD, KEY_ERROR_MESSAGE,
                    "No File Uploaded. Please select a file and upload.");
        } else if (!fileName.toLowerCase().matches(".*\\.lic$|.*\\.txt$")) {
            modelAndView = new ModelAndView(RESPONSE_LICENSE_UPLOAD, KEY_ERROR_MESSAGE,
                    "The uploaded file is not an text file ending with .lic or .txt extension.");
        } else if (file.isEmpty()) {
            modelAndView = new ModelAndView(RESPONSE_LICENSE_UPLOAD, KEY_ERROR_MESSAGE,
                    "The uploaded file does not contain any data.");
        } else {

            try {
                byte[] fileContent = file.getBytes();

                String key = new String(fileContent, Charset.defaultCharset());

                licenseKeyService.setKey(key);

                try {
                    Util.writeFile(PdiConfig.getProperty(Constants.PDI_HOME), fileContent,
                            Constants.LICENSE_FILENAME);
                    LicenseFileValidator.getInstance().resetFileStatus();
                } catch (FileNotFoundException fnfe) {
                    LOGGER.error("Could not locate file.", fnfe);
                } catch (IOException e) {
                    LOGGER.error("Error writing file.", e);
                }

                modelAndView = new ModelAndView("redirect: listProjects.html");

            } catch (LicenseParsingException lpe) {
                LOGGER.error("Exception: ", lpe);
                modelAndView = new ModelAndView(RESPONSE_LICENSE_UPLOAD, KEY_ERROR_MESSAGE,
                        lpe.getMessage() + ".");
            } catch (IOException ioe) {
                LOGGER.error("Exception: ", ioe);
                modelAndView = new ModelAndView(RESPONSE_LICENSE_UPLOAD, KEY_ERROR_MESSAGE,
                        "Error reading uploaded file. Please try upload again.");
            } catch (Exception exception) {
                LOGGER.error("Exception: ", exception);
                modelAndView = new ModelAndView(RESPONSE_LICENSE_UPLOAD, KEY_ERROR_MESSAGE,
                        "Unknown error occurred. Please try upload again.");
            }
        }
    }
    return modelAndView;
}

From source file:eionet.transfer.controller.FileOpsController.java

/**
 * Upload file for transfer./*from   w  w w  . j a va2s . c om*/
 */
@RequestMapping(value = "/fileupload", method = RequestMethod.POST)
public String importFile(@RequestParam("file") MultipartFile myFile, @RequestParam("fileTTL") int fileTTL,
        final RedirectAttributes redirectAttributes, final HttpServletRequest request) throws IOException {

    if (myFile == null || myFile.getOriginalFilename() == null) {
        redirectAttributes.addFlashAttribute("message", "Select a file to upload");
        return "redirect:fileupload";
    }
    if (fileTTL > 90) {
        redirectAttributes.addFlashAttribute("message", "Invalid expiration date");
        return "redirect:fileupload";
    }
    String uuidName = storeFile(myFile, fileTTL);
    redirectAttributes.addFlashAttribute("uuid", uuidName);
    StringBuffer requestUrl = request.getRequestURL();
    redirectAttributes.addFlashAttribute("url",
            requestUrl.substring(0, requestUrl.length() - "/fileupload".length()));
    return "redirect:fileupload";
    //return "redirect:uploadSuccess";
}