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:com.engine.biomine.BiomineController.java

@ApiOperation(
        // Populates the "summary"
        value = "Index multiple documents (from local)",
        // Populates the "description"
        notes = "Add multiple documents to the index (should be compressed in an archive file)")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Accepted", response = Boolean.class),
        @ApiResponse(code = 400, message = "Bad Request", response = BiomineError.class),
        @ApiResponse(code = 500, message = "Internal Server Error", response = BiomineError.class),
        @ApiResponse(code = 503, message = "Service Unavailable", response = BiomineError.class) })
@RequestMapping(value = "/indexer/index/documents", method = RequestMethod.POST, produces = {
        APPLICATION_JSON_VALUE })//  ww  w.jav a2s  .  co m
@ResponseBody
public ResponseEntity<Boolean> indexDocuments(
        @ApiParam(value = "File path", required = true) @RequestParam(value = "path", required = true) MultipartFile path,
        @ApiParam(value = "Collection", required = true) @RequestParam(value = "collection", required = true) String collection) {
    if (!path.isEmpty()) {
        if (IOUtil.getINSTANCE().isValidExtension(path.getOriginalFilename())) {
            logger.info("Start indexing data from path {}", path.getOriginalFilename());
            try {
                File file = new File(path.getOriginalFilename());
                file.createNewFile();

                FileOutputStream output = new FileOutputStream(file);
                output.write(path.getBytes());
                output.close();

                indexer.pushData(file, deleteFile, collection);

            } catch (IOException e) {
                e.printStackTrace();
            }
        } else
            logger.info("File extension not valid. Please select a valid file.");
    } else
        logger.info("File does not exist. Please select a valid file.");
    return new ResponseEntity<Boolean>(true, HttpStatus.OK);
}

From source file:com.dlshouwen.tdjs.content.controller.TdjsArticleController.java

/**
 * //w ww  .  j a  va  2  s . c om
 *
 * @param album 
 * @param bindingResult 
 * @return ajax?
 * @throws Exception 
 */
@RequestMapping(value = "/editAlbum", method = RequestMethod.POST)
public void editArtAlbum(@Valid Album album, HttpServletRequest request, BindingResult bindingResult,
        HttpServletResponse response) throws Exception {
    //      AJAX?
    AjaxResponse ajaxResponse = new AjaxResponse();
    //      ??
    if (bindingResult.hasErrors()) {
        ajaxResponse.bindingResultHandler(bindingResult);
        //           ?
        LogUtils.updateOperationLog(request, OperationType.UPDATE,
                "id" + album.getAlbum_id() + "??"
                        + album.getAlbum_name() + "?"
                        + AjaxResponse.getBindingResultMessage(bindingResult) + "");
        response.setContentType("text/html;charset=utf-8");
        JSONObject obj = JSONObject.fromObject(ajaxResponse);
        response.getWriter().write(obj.toString());
        return;
    }

    String path = "";
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("picture");
    String orgFileName = multipartFile.getOriginalFilename();
    if (multipartFile != null && StringUtils.isNotEmpty(orgFileName)) {
        JSONObject jobj = FileUploadClient.upFile(request, orgFileName, multipartFile.getInputStream());
        if (jobj != null && jobj.getString("responseMessage").equals("OK")) {
            path = jobj.getString("fpath");
        }
    }
    album.setAlbum_coverpath(path);
    //      ????
    Date nowDate = new Date();
    //      ?
    album.setAlbum_updatedate(nowDate);
    album.setAlbum_flag("1");

    //      
    albumDao.updateAlbum(album);
    //      ????
    ajaxResponse.setSuccess(true);
    ajaxResponse.setSuccessMessage("??");

    //URL??
    Map map = new HashMap();
    map.put("URL", "tdjs/tdjsArticle/article");
    ajaxResponse.setExtParam(map);

    //      ?
    LogUtils.updateOperationLog(request, OperationType.UPDATE,
            "id" + album.getAlbum_id() + "??" + album.getAlbum_name());
    response.setContentType("text/html;charset=utf-8");
    JSONObject obj = JSONObject.fromObject(ajaxResponse);
    response.getWriter().write(obj.toString());
}

From source file:com.engine.biomine.BiomineController.java

@ApiOperation(
        // Populates the "summary"
        value = "Index a doc (from local)",
        // Populates the "description"
        notes = "Add a single xml doc to the index")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Accepted", response = Boolean.class),
        @ApiResponse(code = 400, message = "Bad Request", response = BiomineError.class),
        @ApiResponse(code = 500, message = "Internal Server Error", response = BiomineError.class),
        @ApiResponse(code = 503, message = "Service Unavailable", response = BiomineError.class) })
@RequestMapping(value = "/indexer/index/documents/{doc}", method = RequestMethod.POST, produces = {
        APPLICATION_JSON_VALUE })//from  w  ww  . j  av  a  2s . com
@ResponseBody
@ConfigurationProperties()
public ResponseEntity<Boolean> indexDocument(HttpServletResponse response,
        @ApiParam(value = "File path", required = true) @RequestParam(value = "path", required = true) MultipartFile path,
        @ApiParam(value = "Collection", required = true) @RequestParam(value = "collection", required = true) String collection) {
    if (!path.isEmpty()) {
        if (IOUtil.getINSTANCE().isValidExtension(path.getOriginalFilename())) {
            logger.info("Start indexing data from path {}", path.getOriginalFilename());
            try {
                File file = new File(path.getOriginalFilename());
                file.createNewFile();
                deleteFile = true;

                FileOutputStream output = new FileOutputStream(file);
                output.write(path.getBytes());
                output.close();

                indexer.pushData(file, deleteFile, collection);

            } catch (IOException e) {
                e.printStackTrace();
            }
        } else
            logger.info("File extension not valid. Please select a valid file.");
    } else
        logger.info("File does not exist. Please select a valid file.");
    return new ResponseEntity<Boolean>(true, HttpStatus.OK);
}

From source file:com.jlfex.hermes.main.AccountPersonalController.java

/**
 * ?/*  w  ww.j  a va  2 s .  c  o  m*/
 * 
 * @param request
 * @return
 */
@RequestMapping("uploadImage")
@ResponseBody()
public void uploadImage(MultipartHttpServletRequest request) {
    try {
        AppUser curUser = App.current().getUser();
        User user = userInfoService.findByUserId(curUser.getId());
        String label = request.getParameter("label");
        MultipartFile file = request.getFile("file");
        String imgStr = Images.toBase64(Files.getMimeType(file.getOriginalFilename()), file.getBytes());
        userInfoService.saveImage(user, imgStr, com.jlfex.hermes.model.UserImage.Type.AUTH, label);
    } catch (Exception e) {
        Logger.error(e.getMessage(), e);
        throw new ServiceException(e.getMessage(), e);
    }
}

From source file:com.pkrete.locationservice.admin.service.illustrations.ImagesServiceImpl.java

/**
 * Adds the given image object to the database and to the file system.
 *
 * @param image the image to be added/*from w  ww .j av a2 s  .c om*/
 * @return true if and only if the image was successfully added; otherwise
 * false
 */
@Override
public boolean create(Image image) {
    // Set created date
    image.setCreated(new Date());
    // Get path of the images dir
    String path = Settings.getInstance().getImagesPath(image.getOwner().getCode());
    // Get path of the images admin dir
    String adminPath = Settings.getInstance().getImagesPathAdmin(image.getOwner().getCode());

    if (image.getFilePath() != null && image.getFilePath().length() > 0) {
        logger.debug("Move uploaded image file from admin dir to service dir.");
        // Image is moved from admin dir to service dir.
        // FilePath variable contains the name of the image file
        String name = image.getFilePath();
        // Name must be unique
        name = this.getUniqueName(path, name);
        // Path variable must be updated
        image.setPath(name);
        // The image is not external
        image.setIsExternal(false);
        // Absolute target path
        path += image.getPath();
        // Absolute source path
        adminPath += image.getFilePath();
        // Check that the file really exists
        if (!this.adminImageExists(image.getFilePath(), image.getOwner())) {
            logger.warn("Creating image failed, because the given file doesn't exist! Path : {}", adminPath);
            return false;
        }
        logger.info("Move image file : \"{}\" -> \"{}\"", adminPath, path);
        // Try to rename (=move) the file
        if (!fileService.rename(adminPath, path)) {
            logger.warn("Moving image file failed! Creating new image failed!");
            return false;
        }
    } else if (image.getUrl() != null && image.getUrl().length() > 0) {
        // Set path
        image.setPath(image.getUrl());
        // Image is external
        image.setIsExternal(true);
    } else if (image.getFile() != null && image.getFile().getSize() > 0) {
        logger.debug("Add uploaded image file.");
        // User has uploaded a file
        MultipartFile file = image.getFile();
        // Get the name of the file
        String name = file.getOriginalFilename();
        // Name must be unique
        name = this.getUniqueName(path, name);
        // Update path variable
        image.setPath(name);
        // Absolute target path
        path += image.getPath();
        // Image is not external
        image.setIsExternal(false);
        // Create a new File object for the uploaded file
        File imageFile = new File(path);

        logger.info("Write uploaded image file to disk. Path : \"{}\"", path);

        try {
            // Write the uploaded file to disk
            file.transferTo(imageFile);
        } catch (IOException ex) {
            logger.warn("Writing image file to disk failed! Creating image failed!");
            logger.error(ex.getMessage(), ex);
            return false;
        }
        // Check that the file really exists
        if (!fileService.exists(path)) {
            logger.warn("Writing image file to disk failed! File doesn't exist. Path : \"{}\"", path);
            return false;
        }
    }
    // Try to save the image to DB
    if (dao.create(image)) {
        logger.info("Image created : {}", this.jsonizer.jsonize(image, true));
        return true;
    }
    logger.warn("Failed to create image : {}", this.jsonizer.jsonize(image, true));
    return false;
}

From source file:com.dlshouwen.tdjs.picture.controller.TdjsPictureController.java

/**
 * // www  .  j  a v  a 2  s.c  om
 *
 * @param picture 
 * @param bindingResult ?
 * @param request 
 * @return ajax?
 */
@RequestMapping(value = "/{albumId}/ajaxMultipartAdd", method = RequestMethod.POST)
@ResponseBody
public void ajaxAddMultipartPictureAl(@Valid Picture picture, BindingResult bindingResult,
        HttpServletRequest request, HttpServletResponse response, @PathVariable String albumId)
        throws Exception {
    //      AJAX?
    AjaxResponse ajaxResponse = new AjaxResponse();
    String flag = request.getParameter("flag");
    String path = "";
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("file");
    String sname = multipartFile.getOriginalFilename();
    if (multipartFile != null && StringUtils.isNotEmpty(sname)) {
        JSONObject jobj = FileUploadClient.upFile(request, sname, multipartFile.getInputStream());
        if (jobj != null && jobj.getString("responseMessage").equals("OK")) {
            path = jobj.getString("fpath");
        }
    }

    //??
    picture.setPicture_name(sname);

    //      ????
    SessionUser sessionUser = (SessionUser) request.getSession().getAttribute(CONFIG.SESSION_USER);
    String userId = sessionUser.getUser_id();
    String userName = sessionUser.getUser_name();
    Date nowDate = new Date();

    //      ?   
    picture.setPicture_id(new GUID().toString());
    picture.setCreate_time(nowDate);
    picture.setUser_id(userId);
    picture.setUser_name(userName);
    //   path = path.replaceAll("\\\\", "/");
    picture.setPath(path);
    picture.setAlbum_id(albumId);
    picture.setFlag("1");
    picture.setShow("1");

    //
    Album album = albumDao.getAlbumById(albumId);
    String team_id = album.getTeam_id();
    String team_name = album.getTeam_name();
    picture.setTeam_id(team_id);
    picture.setTeam_name(team_name);

    picture.setUpdate_time(new Date());

    //      
    dao.insertPicture(picture);

    //??,????
    if (StringUtils.isNotEmpty(flag) && flag.equals("article")) {
        if (StringUtils.isEmpty(album.getAlbum_coverpath())) {
            albumDao.setAlbCover(albumId, picture.getPath());
        }
    }

    //      ????
    ajaxResponse.setSuccess(true);
    ajaxResponse.setSuccessMessage("??");

    //      ?
    LogUtils.updateOperationLog(request, OperationType.INSERT,
            "?" + picture.getPicture_id());

    response.setContentType("text/html;charset=utf-8");
    JSONObject obj = JSONObject.fromObject(ajaxResponse);
    response.getWriter().write(obj.toString());
    return;
}

From source file:pt.ist.applications.admissions.ui.ApplicationsAdmissionsController.java

@RequestMapping(value = "/candidate/{candidate}/upload", method = RequestMethod.POST)
public String candidateUpload(@PathVariable Candidate candidate, @RequestParam String hash,
        @RequestParam MultipartFile file, @RequestParam String name, final Model model) {
    if (candidate.verifyHashForEdit(hash)) {
        try {//from   ww  w  . j a v a2s.co  m
            final String contentType = file.getContentType();
            final String filename = chooseFileName(name, file.getOriginalFilename(), contentType);
            ClientFactory.configurationDriveClient().upload(candidate.getDirectoryForCandidateDocuments(),
                    filename, file.getInputStream(), contentType);
        } catch (final IOException e) {
            throw new Error(e);
        }
    }
    return "redirect:/admissions/candidate/" + candidate.getExternalId() + "?hash=" + hash;
}

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

@RequestMapping("/headpic/upload")
public void upload(@RequestParam(value = "file", required = false) MultipartFile file, Long userId, Map data,
        HttpServletRequest request, HttpSession httpSession, HttpServletResponse response) throws Exception {

    String extensionName = null;/*w  w  w.ja  v  a2  s  . co m*/
    if (file != null) {
        extensionName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        extensionName = extensionName.replaceAll("\\?\\d+$", "");
    }

    String successFormat = "{\"result\":\"%s\",\"state\":200}";
    String errorFormat = "{\"message\":\"%s\",\"state\":500}";

    Cropper cropper = JSON.parseObject((String) data.get("data"), Cropper.class);

    //?
    if (!".BMP,.JPG,.JPEG,.PNG,.GIF".contains(extensionName.toUpperCase())) {
        WebUtils.writeJson(response,
                String.format(errorFormat, "?,(bmp,jpg,jpeg,png,gif)?"));
        return;
    }

    User user = userService.getUserById(userId);

    if (user == null) {
        WebUtils.writeJson(response, String.format(errorFormat, "??"));
        return;
    }

    String path = httpSession.getServletContext().getRealPath("/") + "upload" + File.separator;

    String picName = user.getUserId() + extensionName.toLowerCase();

    File picFile = new File(path, picName);
    if (!picFile.exists()) {
        picFile.mkdirs();
    }

    try {
        file.transferTo(picFile);
        //?
        Image image = ImageIO.read(picFile);
        if (image == null) {
            WebUtils.writeJson(response, String.format(errorFormat, "?,"));
            picFile.delete();
            return;
        }

        //?
        if (picFile.length() / 1024 / 1024 > 5) {
            WebUtils.writeJson(response,
                    String.format(errorFormat, ",??5M"));
            picFile.delete();
            return;
        }

        //?
        ImageUtils.instance(picFile).rotate(cropper.getRotate())
                .clip(cropper.getX(), cropper.getY(), cropper.getWidth(), cropper.getHeight()).build();

        //?.....
        userService.uploadimg(picFile, userId);
        userService.updateUser(user);

        String contextPath = WebUtils.getWebUrlPath(request);
        String imgPath = contextPath + "/upload/" + picName + "?" + System.currentTimeMillis();
        user.setHeaderPath(imgPath);
        user.setHeaderpic(null);
        httpSession.setAttribute(OpencronTools.LOGIN_USER, user);

        WebUtils.writeJson(response, String.format(successFormat, imgPath));
        logger.info(" upload file successful @ " + picName);
    } catch (Exception e) {
        e.printStackTrace();
        logger.info("upload exception:" + e.getMessage());
    }
}

From source file:net.mindengine.oculus.frontend.web.controllers.report.ReportUploadFileController.java

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setContentType("text/html");
    PrintWriter pw = response.getWriter();
    log.info("uploading file");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {

        DefaultMultipartHttpServletRequest multipartRequest = (DefaultMultipartHttpServletRequest) request;

        int i = 0;
        boolean bNext = true;
        while (bNext) {
            i++;/* w w  w  . j  a  v  a 2  s  .c o  m*/
            MultipartFile multipartFile = multipartRequest.getFile("file" + i);
            if (multipartFile != null) {
                fileId++;
                Date date = new Date();
                String path = FileUtils.generatePath(date);
                String fullDirPath = config.getDataFolder() + File.separator + path;
                File dir = new File(fullDirPath);
                dir.mkdirs();
                //FileUtils.mkdirs(config.getDataFolder() + File.separator + path);

                String fileType = FileUtils.getFileType(multipartFile.getOriginalFilename()).toLowerCase();
                path += File.separator + date.getTime() + "_" + fileId + "." + fileType;

                File file = new File(config.getDataFolder() + File.separator + path);
                file.createNewFile();

                FileOutputStream fos = new FileOutputStream(file);
                fos.write(multipartFile.getBytes());
                fos.close();

                if (fileType.equals("png") || fileType.equals("jpg") || fileType.equals("gif")
                        || fileType.equals("bmp")) {
                    pw.println("[uploaded]?type=image-" + fileType + "&object=" + date.getTime() + "&item="
                            + fileId);
                }
                if (fileType.equals("txt") || fileType.equals("json") || fileType.equals("xml")) {
                    pw.println("[uploaded]?type=text-" + fileType + "&object=" + date.getTime() + "&item="
                            + fileId);
                }
            } else
                bNext = false;
        }
    } else
        pw.print("[error]not a multipart content");
    return null;
}

From source file:de.iteratec.iteraplan.presentation.dialog.ExcelImport.ImportFrontendServiceImpl.java

/**
 * @param memBean/*w w w . j a v a 2s  .c  o m*/
 * @return true if successful, false if not.
 */
private boolean handleUploadedFile(MassdataMemBean memBean) {
    memBean.resetResultMessages();
    MultipartFile file = memBean.getFileToUpload();
    if (file == null || file.getSize() == 0) {
        memBean.addErrorMessage(MessageAccess.getString("import.no.file"));
        return false;
    }
    if (memBean.getImportStrategy() == null) {
        memBean.addErrorMessage(MessageAccess.getString("import.no.strategy"));
        return false;
    }
    //TODO use the import strategy

    String originalFilename = file.getOriginalFilename();
    memBean.setFileName(originalFilename);

    if (determineImportType(memBean, originalFilename)) {
        if (file.getSize() > MAX_FILESIZE_BYTE) {
            memBean.addErrorMessage(MessageFormat.format(MessageAccess.getString("import.too.large"),
                    Long.valueOf(MAX_FILESIZE_BYTE)));
            return false;
        }

        setFileContentToMemBean(memBean, file);
        return true;
    }

    return false;
}