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.cloudbees.demo.beesshop.web.ProductController.java

/**
 * @param id    id of the product/*from  w w w .j av a2  s .co m*/
 * @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:org.shaf.server.controller.ActionApplicationController.java

/**
 * Deploys an application to the server.
 * /*from w  ww  . ja v a  2 s .  c  o m*/
 * @param file
 *            the deploying package.
 * @return the view model.
 * @throws Exception
 *             is the view constructing has failed.
 */
@RequestMapping(value = "/deploy", method = RequestMethod.POST)
public ModelAndView onDeploy(@RequestParam("file") MultipartFile file) throws Exception {
    LOG.debug("CALL: /app/action/deploy (with attached multipart-file object)");

    ViewApplication view = ViewApplication.getListView().header("cloud",
            "All currently deployed applications.");

    if (!file.isEmpty()) {
        String app = file.getOriginalFilename();
        if (OPER.deployApplication(app, file.getBytes())) {
            view.info("The '" + app + "' application is deployed. ");
        } else {
            view.warn("The '" + app + "' application is not deployed yet. "
                    + "(Check the log to clarify a problem.)");
        }
    } else {
        view.warn("Select an application for deployment " + "(click on 'Browse' button).");
    }

    return view.addApplicationList(OPER.getApplications());
}

From source file:com.wipro.ats.bdre.md.rest.TDUploaderAPI.java

@RequestMapping(value = "/uploadtr/{processIdValue}", method = RequestMethod.POST)
@ResponseBody/*from www . ja  v  a  2  s.  c  om*/
public RestWrapper uploadInTeradata(@PathVariable("processIdValue") Integer processIdValue,
        @RequestParam("file") MultipartFile file, Principal principal) {

    if (!file.isEmpty()) {
        try {

            String uploadedFilesDirectory = MDConfig.getProperty(UPLOADBASEDIRECTORY);
            String name = file.getOriginalFilename();
            byte[] bytes = file.getBytes();
            String monitorPath = null;
            LOGGER.info("processIDvalue is " + processIdValue);
            com.wipro.ats.bdre.md.dao.jpa.Process process = processDAO.get(processIdValue);
            LOGGER.info("Process fetched = " + process.getProcessId());
            List<Properties> propertiesList = propertiesDAO.getByProcessId(process);
            LOGGER.info("No.of Properties fetched= " + propertiesList.size());
            for (Properties property : propertiesList) {
                LOGGER.debug(
                        "property fetched is " + property.getId().getPropKey() + " " + property.getPropValue());
                if ("monitored-dir-name".equals(property.getId().getPropKey())) {
                    monitorPath = property.getPropValue();
                }
            }
            String uploadLocation = monitorPath;
            LOGGER.info("Upload location: " + uploadLocation);
            File fileDir = new File(uploadLocation);
            fileDir.mkdirs();
            File fileToBeSaved = new File(uploadLocation + "/" + name);
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileToBeSaved));
            stream.write(bytes);
            stream.close();
            LOGGER.debug("Uploaded file: " + fileToBeSaved);

            //Populating Uploaded file bean to return in RestWrapper
            UploadedFile uploadedFile = new UploadedFile();
            uploadedFile.setParentProcessId(processIdValue);
            // uploadedFile.setSubDir(subDir);
            uploadedFile.setFileName(name);
            uploadedFile.setFileSize(fileToBeSaved.length());
            LOGGER.debug("The UploadedFile bean:" + uploadedFile);
            LOGGER.info("File uploaded : " + uploadedFile + " uploaded by User:" + principal.getName());

            return new RestWrapper(uploadedFile, RestWrapper.OK);
        } catch (Exception e) {
            LOGGER.error(e);
            return new RestWrapper(e.getMessage(), RestWrapper.ERROR);
        }
    } else {
        return new RestWrapper("You failed to upload because the file was empty.", RestWrapper.ERROR);

    }
}

From source file:com.dlshouwen.tdjs.album.controller.TdjsAlbumController.java

/**
 * /*from  ww w  . j av a2 s. c o m*/
 *
 * @param album 
 * @param bindingResult 
 * @param request 
 * @return ajax?
 * @throws Exception 
 */
@RequestMapping(value = "/add", method = RequestMethod.POST)
public void addAlbum(@Valid Album album, BindingResult bindingResult, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    AjaxResponse ajaxResponse = new AjaxResponse();

    if (bindingResult.hasErrors()) {
        ajaxResponse.bindingResultHandler(bindingResult);
        LogUtils.updateOperationLog(request, OperationType.INSERT,
                "??" + 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);

    //      ????
    SessionUser sessionUser = (SessionUser) request.getSession().getAttribute(CONFIG.SESSION_USER);
    String userName = sessionUser.getUser_name();
    String userId = sessionUser.getUser_id();
    Date nowDate = new Date();
    //      ?????
    album.setAlbum_id(new GUID().toString());
    album.setAlbum_createuser(userName);
    album.setAlbum_createuserbyid(userId);
    album.setAlbum_createdate(nowDate);

    //      
    dao.insertAlbum(album);
    //      ????
    ajaxResponse.setSuccess(true);
    ajaxResponse.setSuccessMessage("??");

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

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

From source file:uk.ac.bbsrc.tgac.browser.web.UploadController.java

public void uploadFile(Class type, String qualifier, MultipartFile fileItem) throws IOException {
    log.info("uploadfile 1.1");

    File dir = new File(filesManager.getFileStorageDirectory() + File.separator
            + type.getSimpleName().toLowerCase() + File.separator + qualifier);
    if (filesManager.checkDirectory(dir, true)) {
        log.info("Attempting to store " + dir.toString() + File.separator + fileItem.getOriginalFilename());
        fileItem.transferTo(/*from  www. j  a v a 2  s .  c o m*/
                new File(dir + File.separator + fileItem.getOriginalFilename().replaceAll("\\s", "_")));
    } else {
        throw new IOException(
                "Cannot upload file - check that the directory specified in miso.properties exists and is writable");
    }
    log.info("uploadfile 1.2");

}

From source file:org.catrobat.catroid.HomeController.java

@RequestMapping(value = "/*", method = RequestMethod.POST)
public String Upload(@RequestParam(value = "file", required = true) MultipartFile file, Model model,
        HttpServletRequest request) throws IOException {

    if (file == null)
        return home(model, request);
    if (!isCatrobatFile(file.getOriginalFilename())) {
        return error(model, "Illegal file!",
                "File you tried to upload is not .catrobat file. Please, upload catrobat project (e. g.\"project.catrobat\")");

    }/*from  w  w  w.  j  a  v  a  2s  . c om*/

    String appFolder = request.getSession().getServletContext().getRealPath("/");
    String uploadFolder = getUploadFolder(request);

    try {
        createProjectDir(appFolder, uploadFolder);
    } catch (UploadException e1) {
        return error(model, "Cannot create directory for project",
                "Oops, it seems we have some internal error. Please, try one more time and do mot hurry.");
    }

    String filePath = appFolder + uploadFolder + "\\" + file.getOriginalFilename();

    FileOutputStream outputStream = null;
    try {
        outputStream = new FileOutputStream(new File(filePath));
        outputStream.write(file.getBytes());
        outputStream.close();
    } catch (Exception e) {
        return error(model, "Cannot save file", e.getStackTrace().toString());
    }

    setPathsToSesisionAttributes(request, appFolder, uploadFolder);

    ZipFile zip;
    try {
        zip = new ZipFile(filePath);
        zip.extractAll(appFolder + uploadFolder);
    } catch (ZipException e) {
        return error(model, "Cannot unzip project file", e.getStackTrace().toString());
    }

    return home(model, request);
}

From source file:ch.ralscha.extdirectspring_itest.FileUploadController.java

@ExtDirectMethod(value = ExtDirectMethodType.FORM_POST, group = "itest_upload", event = "test", entryClass = String.class, synchronizeOnSession = true)
@RequestMapping(value = "/test", method = RequestMethod.POST)
public void uploadTest(HttpServletRequest request, @RequestParam("fileUpload") MultipartFile file,
        final HttpServletResponse response, @Valid User user, BindingResult result) throws IOException {

    ExtDirectResponseBuilder builder = new ExtDirectResponseBuilder(request, response);

    if (file != null && !file.isEmpty()) {
        builder.addResultProperty("fileContents", new String(file.getBytes()));
        builder.addResultProperty("fileName", file.getOriginalFilename());
    }/* w  w  w .j av  a2  s  . c o m*/
    builder.addErrors(result);
    builder.addResultProperty("name", user.getName());
    builder.addResultProperty("firstName", user.getFirstName());
    builder.addResultProperty("age", user.getAge());
    builder.addResultProperty("email", user.getEmail());

    builder.successful();
    builder.buildAndWrite();
}

From source file:service.ArticleService.java

public ServiceResult save(Article obj, MultipartFile file) throws IOException {
    ServiceResult result = new ServiceResult();
    validateSave(obj, dao, result);/*  w w  w  .  jav a  2  s .  c  om*/
    if (result.hasErrors()) {
        if (file != null && !file.isEmpty()) {
            ArticleFile articleFile = new ArticleFile();
            articleFile.setArticle(obj);
            articleFile.setRusname(file.getOriginalFilename());
            saveFile(articleFile, file);
        }
    }
    return result;
}