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:hr.softwarecity.osijek.controllers.PersonController.java

/**
 * Method for user image upload//from   ww  w  . j av a 2 s . co  m
 * @param id
 * @param file
 * @return HTTP OK or HTTP
 */
@RequestMapping(value = "/{id}/image", method = RequestMethod.POST)
public ResponseEntity<HashMap<String, String>> setUserImage(@PathVariable("id") long id,
        @RequestParam("file") MultipartFile file) {
    String path = null;
    try {
        path = Multimedia.handleFileUpload("/var/www/html/app/img", file);
    } catch (IOException ex) {
        Logger.getLogger("PersonController.java").log(Logger.Level.ERROR,
                "File failed to upload, cannot write to path");
    }
    if (path != null) {
        path = "/app/img/" + file.getOriginalFilename();
        Person person = personRepository.findById(id);
        person.setImage(path);
        personRepository.save(person);
        Logger.getLogger("PersonController.java").log(Logger.Level.INFO, "New user image saved");
        HashMap<String, String> map = new HashMap<>();
        map.put("path", path);
        return new ResponseEntity<>(map, HttpStatus.OK);
    } else {
        return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
    }
}

From source file:com.card.loop.xyz.controller.LearningObjectController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(@RequestParam(value = "title") String title, @RequestParam("author") String author,
        @RequestParam("description") String description, @RequestParam("file") MultipartFile file,
        @RequestParam("type") String type) {
    if (!file.isEmpty()) {
        try {/*from w w  w . j  a va2 s  . co m*/
            byte[] bytes = file.getBytes();
            File fil = new File(AppConfig.UPLOAD_BASE_PATH + file.getOriginalFilename());
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fil));
            stream.write(bytes);
            stream.close();

            LearningObject lo = new LearningObject();
            System.out.println(title);
            System.out.println(author);
            System.out.println(description);

            lo.setTitle(title);
            lo.setUploadedBy(author);
            lo.setDateUpload(new Date());
            lo.setDescription(description);
            lo.setStatus(0);
            lo.setDownloads(0);
            lo.setRating(1);

            System.out.println("UPLOAD LO FINISHED");

        } catch (Exception e) {
            System.err.println(e.toString());
        }
    } else {
        System.err.println("EMPTY FILE.");
    }

    return "redirect:/developer-update";
}

From source file:com.hs.mail.web.controller.WebConsole.java

private ModelAndView doImportAccounts(WebSession session) {
    MultipartHttpServletRequest multi = (MultipartHttpServletRequest) session.getRequest();
    DataImporter importer = new DataImporter();
    MultipartFile mf = multi.getFile("file");
    if (mf != null) {
        try {/*from  w  w  w.  java  2s. c  om*/
            session.removeBeans(WebSession.ACCOUNT_COUNT);
            importer.importAccount(manager, mf.getInputStream());
        } catch (IOException e) {
            importer.addError(0, mf.getOriginalFilename(), e);
        }
    }
    if (importer.hasErrors()) {
        return new ModelAndView("importerror", "errors", importer.getErrors());
    } else {
        return getRedirectView(session);
    }
}

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

public String saveAttachmentSimple(HttpServletRequest request) throws BusinessException {
    StringBuffer r = new StringBuffer();
    try {//from   www.j  a  va  2  s  . c o  m
        CustomMultipartResolver multipartResolver = new CustomMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            String path = request.getSession().getServletContext()
                    .getRealPath(com.pantuo.util.Constants.FILE_UPLOAD_DIR).replaceAll("WEB-INF", "");
            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();
                    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);
                        if (r.length() == 0) {
                            r.append(p.getRight());
                        } else {
                            r.append(";" + p.getRight());
                        }
                    }
                }
            }
        }
        return r.toString();
    } catch (Exception e) {
        log.error("saveAttachmentSimple", e);
        throw new BusinessException("saveAttachment-error", e);
    }
}

From source file:ua.aits.sdolyna.controller.SystemController.java

@RequestMapping(value = { "/Sdolyna/system/do/uploadimage", "/system/do/uploadimage",
        "/Sdolyna/system/do/uploadimage/", "/system/do/uploadimage/" }, method = RequestMethod.POST)
public @ResponseBody String uploadImageHandler(@RequestParam("file") MultipartFile file,
        @RequestParam("path") String path, HttpServletRequest request) {
    Integer curent = Integer.parseInt(Helpers.lastFileModified(Constants.home + path).getName().split("\\.")[0])
            + 1;/*from   w w w  . j  a  v  a 2 s.  c  o  m*/
    String ext = file.getOriginalFilename().split("\\.")[1];
    String name = curent.toString() + "." + ext;
    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();
            File dir = new File(Constants.home + path);
            if (!dir.exists())
                dir.mkdirs();
            File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
            try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) {
                stream.write(bytes);
            }
            return name;
        } catch (Exception e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name + " because the file was empty.";
    }
}

From source file:ua.aits.sdolyna.controller.SystemController.java

@RequestMapping(value = { "/Sdolyna/system/do/uploadfile", "/system/do/uploadfile",
        "/Sdolyna/system/do/uploadfile/", "/system/do/uploadfile/" }, method = RequestMethod.POST)
public @ResponseBody String uploadFileHandler(@RequestParam("file") MultipartFile file,
        @RequestParam("path") String path, HttpServletRequest request) {
    Integer curent = Integer.parseInt(Helpers.lastFileModified(Constants.home + path).getName().split("\\.")[0])
            + 1;//from ww w.  ja  v a  2  s .  c om
    String ext = file.getOriginalFilename().split("\\.")[1];
    String name = curent.toString() + "." + ext;
    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();
            File dir = new File(Constants.home + path);
            if (!dir.exists())
                dir.mkdirs();
            File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
            try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) {
                stream.write(bytes);
            }
            return name;
        } catch (Exception e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name + " because the file was empty.";
    }
}

From source file:app.service.ResourceService.java

public int upload(MultipartFile file, int resourceType, StringResource resource) {
    if (file.isEmpty()) {
        return ResultCode.FILE_EMPTY;
    }/*from ww  w .  ja v  a2s.  co m*/

    String path;
    if (resourceType == RESOURCE_TYPE_AVATAR) {
        path = RESOURCE_AVATAR_PATH;
    } else if (resourceType == RESOURCE_TYPE_COMMON) {
        path = RESOURCE_COMMON_PATH;
    } else {
        return ResultCode.UNKNOWN_RESOURCE;
    }

    resolvePath(path);
    String filename = resolveFilename(file.getOriginalFilename());
    try {
        OutputStream out = new FileOutputStream(new File(path + "/" + filename));
        BufferedOutputStream stream = new BufferedOutputStream(out);
        FileCopyUtils.copy(file.getInputStream(), stream);
        stream.close();
        resource.filename = filename;
    } catch (Exception e) {
        logger.warn("upload file failure", e);
        return ResultCode.UPLOAD_FILE_FAILED;
    }
    return BaseResponse.COMMON_SUCCESS;
}

From source file:ua.aits.sdolyna.controller.SystemController.java

@RequestMapping(value = { "/Sdolyna/uploadFile", "/uploadFile", "/Sdolyna/uploadFile/",
        "/uploadFile/" }, method = RequestMethod.POST)
public @ResponseBody String uploadFileHandlerFull(@RequestParam("upload") MultipartFile file,
        @RequestParam("path") String path, HttpServletRequest request) {
    Integer curent = Integer.parseInt(Helpers.lastFileModified(Constants.home + path).getName().split("\\.")[0])
            + 1;/*  w  w w .j av  a 2 s. c  o m*/
    String ext = file.getOriginalFilename().split("\\.")[1];
    String name = curent.toString() + "." + ext;
    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();
            // Creating the directory to store file
            File dir = new File(Constants.home + path);
            if (!dir.exists())
                dir.mkdirs();

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
            try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) {
                stream.write(bytes);
            }
            String link_path = serverFile.getAbsolutePath().replace(Constants.home, "");
            return "<img class=\"main-img\" src=\"" + Constants.URL + link_path + "\" realpath='" + link_path
                    + "'  alt='" + link_path + file.getName() + "'  />";
        } catch (Exception e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name + " because the file was empty.";
    }
}

From source file:org.openmrs.module.webservices.rest.web.v1_0.resource.openmrs1_8.ModuleResource1_8.java

@Override
public Object upload(MultipartFile file, RequestContext context) throws ResponseException, IOException {
    moduleFactoryWrapper.checkPrivilege();

    File moduleFile = null;//from  ww w  .  j  a  v  a2 s.  co  m
    Module module = null;

    try {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("Uploaded OMOD file cannot be empty");
        } else {
            String filename = WebUtil.stripFilename(file.getOriginalFilename());
            Module tmpModule = moduleFactoryWrapper.parseModuleFile(file);
            Module existingModule = moduleFactoryWrapper.getModuleById(tmpModule.getModuleId());
            ServletContext servletContext = context.getRequest().getSession().getServletContext();

            if (existingModule != null) {
                List<Module> dependentModulesStopped = moduleFactoryWrapper
                        .stopModuleAndGetDependent(existingModule);

                for (Module depMod : dependentModulesStopped) {
                    moduleFactoryWrapper.stopModuleSkipRefresh(depMod, servletContext);
                }

                moduleFactoryWrapper.stopModuleSkipRefresh(existingModule, servletContext);
                moduleFactoryWrapper.unloadModule(existingModule);
            }

            moduleFile = moduleFactoryWrapper.insertModuleFile(tmpModule, filename);
            module = moduleFactoryWrapper.loadModule(moduleFile);
            moduleFactoryWrapper.startModule(module, servletContext);
            return getByUniqueId(tmpModule.getModuleId());
        }
    } finally {
        if (module == null && moduleFile != null) {
            FileUtils.deleteQuietly(moduleFile);
        }
    }
}

From source file:org.jasig.portlet.cms.controller.EditPostController.java

private void processPostAttachments(final ActionRequest request, final Post post) throws Exception {
    if (FileUploadBase.isMultipartContent(new PortletRequestContext(request))) {

        /*/*from   w  ww  .  j a v  a  2s .  c om*/
         * Attachments may have been removed in the edit mode. We must
         * refresh the session-bound post before updating attachments.
         */
        final PortletPreferencesWrapper pref = new PortletPreferencesWrapper(request);
        final Post originalPost = getRepositoryDao().getPost(pref.getPortletRepositoryRoot());

        if (originalPost != null) {
            post.getAttachments().clear();
            post.getAttachments().addAll(originalPost.getAttachments());
        }

        final MultipartActionRequest multipartRequest = (MultipartActionRequest) request;

        for (int index = 0; index < multipartRequest.getFileMap().size(); index++) {
            final MultipartFile file = multipartRequest.getFile("attachment" + index);

            if (!file.isEmpty()) {

                logDebug("Uploading attachment file: " + file.getOriginalFilename());
                logDebug("Attachment file size: " + file.getSize());

                final Calendar cldr = Calendar.getInstance(request.getLocale());
                cldr.setTime(new Date());
                final Attachment attachment = Attachment.fromFile(file.getOriginalFilename(),
                        file.getContentType(), cldr, file.getBytes());

                final String title = multipartRequest.getParameter("attachmentTitle" + index);
                attachment.setTitle(title);
                post.getAttachments().add(attachment);
            }

        }
    }
}