Example usage for org.springframework.web.multipart MultipartFile isEmpty

List of usage examples for org.springframework.web.multipart MultipartFile isEmpty

Introduction

In this page you can find the example usage for org.springframework.web.multipart MultipartFile isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Return whether the uploaded file is empty, that is, either no file has been chosen in the multipart form or the chosen file has no content.

Usage

From source file:com.newline.view.company.controller.CompanyController.java

/**
 * /*  w  w  w .j  a  va  2  s.c o m*/
 * ????
 * 
 * @param request
 * @param company
 * @param file
 * @return
 * @see 
 * @author  2015-9-17?6:04:12
 * @since 1.0
 */
@RequestMapping("/saveOrUpdaeCompanyMainInfo")
public String saveOrUpdaeCompanyMainInfo(HttpServletRequest request, NlCompanyEntity company,
        @RequestParam(value = "mylogo", required = false) MultipartFile file) {
    NlMemberEntity member = getMember(request);
    if (member != null) {
        NlCompanyEntity sourcecompany = companyService.getCompanyByMemberid(member.getId());
        copyCompanyInfo(sourcecompany, company);
        if (!file.isEmpty()) {
            String logo = QiNiuUtils.uploadImg(file);
            if (StringUtils.isNotBlank(sourcecompany.getLogo())) {
                QiNiuUtils.delete(sourcecompany.getLogo());
            }
            sourcecompany.setLogo(logo);
        }
        companyService.updateCompany(sourcecompany);
    }
    return "redirect:/company/goCompanyMainPage?type=maininfo";

}

From source file:com.balero.controllers.UploadController.java

/**
 * Upload image from CKEDITOR to server/*from   ww w.  j  a v a  2 s  .com*/
 *
 * Source: http://alfonsoml.blogspot.mx/2013/08/a-basic-
 * upload-script-for-ckeditor.html
 *
 * @param file HTML <input>
 * @param model Framework model layer
 * @param request HTTP headers
 * @param baleroAdmin Magic cookie
 * @return view
 */
@RequestMapping(value = "/picture", method = RequestMethod.POST)
public String uploadPicture(@RequestParam("upload") MultipartFile file, Model model, HttpServletRequest request,
        @CookieValue(value = "baleroAdmin", defaultValue = "init") String baleroAdmin) {

    // Security
    UsersAuth security = new UsersAuth();
    security.setCredentials(baleroAdmin, UsersDAO);
    boolean securityFlag = security.auth(baleroAdmin, security.getLocalUsername(), security.getLocalPassword());
    if (!securityFlag)
        return "hacking";

    String CKEditorFuncNum = request.getParameter("CKEditorFuncNum");

    String inputFileName = file.getOriginalFilename();

    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            //String rootPath = System.getProperty("catalina.home");
            File dir = new File("../webapps/media/pictures");
            if (!dir.exists())
                dir.mkdirs();

            String[] ext = new String[9];
            // Add your extension here
            ext[0] = ".jpg";
            ext[1] = ".png";
            ext[2] = ".bmp";
            ext[3] = ".jpeg";

            for (int i = 0; i < ext.length; i++) {
                int intIndex = inputFileName.indexOf(ext[i]);
                if (intIndex == -1) {
                    System.out.println("File extension is not valid");
                } else {
                    // Create the file on server
                    File serverFile = new File(dir.getAbsolutePath() + File.separator + inputFileName);
                    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
                    stream.write(bytes);
                    stream.close();
                }
            }

            System.out.println("You successfully uploaded file");

        } catch (Exception e) {
            System.out.println("You failed to upload => " + e.getMessage());
        }
    } else {
        System.out.println("You failed to upload because the file was empty.");
    }

    //String url = request.getLocalAddr();

    model.addAttribute("url", "/media/pictures/" + inputFileName);
    model.addAttribute("CKEditorFuncNum", CKEditorFuncNum);

    return "upload";

}

From source file:org.shareok.data.webserv.JournalDataController.java

@RequestMapping(value = "/dspace/safpackage/doi/generate", method = RequestMethod.POST)
public ModelAndView safPackageGenerateByDois(HttpServletRequest request, RedirectAttributes redirectAttrs,
        @RequestParam(value = "multiDoiUploadFile", required = false) MultipartFile file) {
    String singleDoi = (String) request.getParameter("singleDoi");
    String multiDoi = (String) request.getParameter("multiDoi");
    String safPaths = null;/*from   w ww  .j a va  2 s  .  c o  m*/
    ByteArrayInputStream stream = null;

    ModelAndView model = new ModelAndView();
    RedirectView view = new RedirectView();
    view.setContextRelative(true);

    if ((null != file && !file.isEmpty()) || null != singleDoi || null != multiDoi) {
        String safFilePath = null;
        try {
            String[] dois;
            if (null != singleDoi) {
                String doi = (String) request.getParameter("doiInput");
                if (null == doi || doi.equals("")) {
                    throw new EmptyDoiInformationException("Empty information from single DOI submission!");
                }
                dois = new String[] { doi };
            } else if (null != multiDoi) {
                String doi = (String) request.getParameter("multiDoiInput");
                if (null == doi || doi.equals("")) {
                    throw new EmptyDoiInformationException("Empty information from multiple DOI submission!");
                }
                dois = doi.trim().split("\\s*;\\s*");
            } else if (null != file && !file.isEmpty()) {
                stream = new ByteArrayInputStream(file.getBytes());
                String doiString = IOUtils.toString(stream, "UTF-8");
                dois = doiString.trim().split("\\s*\\r?\\n\\s*");
            } else {
                throw new EmptyDoiInformationException("Empty DOI information from unknown DOI submission!");
            }
            if (dois != null && dois.length > 0) {

            }
        } catch (Exception ex) {
            logger.error("Cannot generate the SAF packages by the DOIs", ex);
        } finally {
            if (null != stream) {
                try {
                    stream.close();
                } catch (IOException ex) {
                    logger.error("Cannot close the input stream when reading the file containing the DOIs", ex);
                }
            }
        }
        if (null != safFilePath && !safFilePath.equals("")) {
            redirectAttrs.addFlashAttribute("safFilePath", safFilePath);
            view.setUrl(".jsp");
            model.setView(view);
        } else {
            redirectAttrs.addFlashAttribute("errorMessage", "The saf file path is invalid");
            view.setUrl("journalDataUpload.jsp");
            model.setView(view);
        }
    } else {
        redirectAttrs.addFlashAttribute("errorMessage", "The server information is empty");
        view.setUrl("errors/serverError.jsp");
        model.setView(view);
    }
    return model;
}

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;//w  ww. j av  a2  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:org.shareok.data.webserv.SshDspaceDataController.java

@RequestMapping(value = "/ssh/dspace/saf/job/{jobTypeStr}", method = RequestMethod.POST)
public ModelAndView sshDspaceSafImport(HttpServletRequest request,
        @ModelAttribute("SpringWeb") DspaceSshHandler handler,
        @RequestParam(value = "saf", required = false) MultipartFile file,
        @PathVariable("jobTypeStr") String jobTypeStr) {
    String safLink = (String) request.getParameter("saf-online");
    String oldJobId = (String) request.getParameter("old-jobId");
    String userId = String.valueOf(request.getSession().getAttribute("userId"));

    if (null == safLink || safLink.equals("")) {
        safLink = "job-" + oldJobId;
    }//from   ww  w  .  ja  va2  s  . c  o m

    String serverId = handler.getServerId();
    if (null == serverId || serverId.equals("")) {
        String serverName = (String) request.getParameter("serverName");
        if (null != serverName) {
            handler.setServerId(String.valueOf(serverService.findServerIdByName(serverName)));
        }
    }

    if ((null != file && !file.isEmpty()) || (null != safLink && !"".equals(safLink))) {
        try {
            int jobTypeIndex = DataUtil.getJobTypeIndex(jobTypeStr, "dspace");
            handler.setJobType(jobTypeIndex);
            RedisJob job = taskManager.execute(Long.valueOf(userId), handler, file, safLink);

            int statusIndex = job.getStatus();
            String isFinished = (statusIndex == 2 || statusIndex == 6) ? "true" : "false";

            ModelAndView model = new ModelAndView();
            model.setViewName("jobReport");
            model.addObject("host", handler.getSshExec().getServer().getHost());
            model.addObject("collection", handler.getCollectionId());
            model.addObject("repoType", "DSpace");
            model.addObject("isFinished", isFinished);
            model.addObject("reportPath", "/webserv/download/report/" + DataUtil.JOB_TYPES[jobTypeIndex] + "/"
                    + String.valueOf(job.getJobId()));
            WebUtil.outputJobInfoToModel(model, job);

            return model;
        } catch (Exception e) {
            logger.error("Cannot import the SAF package into the DSpace server.", e);
        }
    } else {
        return null;
    }
    return null;
}

From source file:com.gisnet.cancelacion.web.controller.NotarioController.java

@RequestMapping(value = "/notario/caso/{numeroCaso}/aceptar", method = RequestMethod.POST)
public String agregaArchivos(@PathVariable String numeroCaso, Model model,
        RedirectAttributes redirectAttributes, @RequestParam("file1") MultipartFile file1,
        @RequestParam("file2") MultipartFile file2, @RequestParam("file3") MultipartFile file3,
        @RequestParam("file4") MultipartFile file4, @RequestParam("file5") MultipartFile file5) {
    List<String> mensajes = Utils.getFlashMensajes(model, redirectAttributes);
    try {/*from   ww  w . ja  v a  2s  .c o m*/
        sesionSetCaso(numeroCaso);
    } catch (CancelacionWebException | NullPointerException ex) {
        mensajes.add("warning::El caso " + numeroCaso + " no existe.");
        return "redirect:/";
    }
    CasoInfo caso = sesion.getCasoInfo();
    model.addAttribute("caso", caso);

    // guarda archivos
    sesion.getCancelacionArchivos().clear();
    if (!file1.isEmpty()) {
        try {
            guardaCancelacionArchivo(file1);
        } catch (IOException ex) {
            return "redirect:/";
        }
    }
    if (!file2.isEmpty()) {
        try {
            guardaCancelacionArchivo(file2);
        } catch (IOException ex) {
            return "redirect:/";
        }
    }
    if (!file3.isEmpty()) {
        try {
            guardaCancelacionArchivo(file3);
        } catch (IOException ex) {
            return "redirect:/";
        }
    }
    if (!file4.isEmpty()) {
        try {
            guardaCancelacionArchivo(file4);
        } catch (IOException ex) {
            return "redirect:/";
        }
    }
    if (!file5.isEmpty()) {
        try {
            guardaCancelacionArchivo(file5);
        } catch (IOException ex) {
            return "redirect:/";
        }
    }
    return "redirect:/notario/caso/" + numeroCaso + "/aceptar/jefecobranza";
}

From source file:org.opentravel.pubs.controllers.AdminController.java

@RequestMapping({ "/DoUploadCodeList.html", "/DoUploadCodeList.htm" })
public String doUploadCodeListPage(HttpSession session, Model model, RedirectAttributes redirectAttrs,
        @ModelAttribute("codeListForm") CodeListForm codeListForm,
        @RequestParam(value = "archiveFile", required = false) MultipartFile archiveFile) {
    String targetPage = "uploadCodeList";
    try {/* ww w . j  a  v a 2 s . c o  m*/
        if (codeListForm.isProcessForm()) {
            CodeList codeList = new CodeList();

            try {
                codeList.setReleaseDate(CodeList.labelFormat.parse(codeListForm.getReleaseDateLabel()));

                if (!archiveFile.isEmpty()) {
                    DAOFactoryManager.getFactory().newCodeListDAO().publishCodeList(codeList,
                            archiveFile.getInputStream());

                    model.asMap().clear();
                    redirectAttrs.addAttribute("releaseDate", codeList.getReleaseDateLabel());
                    targetPage = "redirect:/admin/ViewCodeList.html";

                } else {
                    ValidationResults vResults = ModelValidator.validate(codeList);

                    // An archive file must be provided on initial creation of a publication
                    vResults.add(codeList, "archiveFilename", "Archive File is Required");

                    if (vResults.hasViolations()) {
                        throw new ValidationException(vResults);
                    }
                }

            } catch (ParseException e) {
                ValidationResults vResult = new ValidationResults();

                vResult.add(codeList, "releaseDate", "Invalid release date");
                addValidationErrors(vResult, model);

            } catch (ValidationException e) {
                addValidationErrors(e, model);

            } catch (Throwable t) {
                log.error("An error occurred while publishing the code list: ", t);
                setErrorMessage(t.getMessage(), model);
            }
        }

    } catch (Throwable t) {
        log.error("Error during publication controller processing.", t);
        setErrorMessage(DEFAULT_ERROR_MESSAGE, model);
    }
    return applyCommonValues(model, targetPage);
}

From source file:org.shareok.data.webserv.SshIslandoraDataController.java

@RequestMapping(value = "/ssh/islandora/book/import/job/{jobTypeStr}", method = RequestMethod.POST)
public ModelAndView sshIslandoraImport(HttpServletRequest request,
        @ModelAttribute("SpringWeb") IslandoraSshHandler handler,
        @RequestParam(value = "recipeLocal", required = false) MultipartFile file,
        @PathVariable("jobTypeStr") String jobTypeStr) {
    String recipeFileUri = (String) request.getParameter("recipeFileUri");
    String userId = String.valueOf(request.getSession().getAttribute("userId"));

    String serverId = handler.getServerId();
    IslandoraRepoServer server = (IslandoraRepoServer) serverService.findServerById(Integer.valueOf(serverId));
    if (null == serverId || serverId.equals("")) {
        String serverName = (String) request.getParameter("serverName");
        if (null != serverName) {
            server = (IslandoraRepoServer) serverService.findServerByName(serverName);
            handler.setServerId(String.valueOf(server.getServerId()));
        }/*ww w  . java2s .  c om*/
    }
    handler.setDrupalDirectory(server.getDrupalPath());
    handler.setFilePath(server.getIslandoraUploadPath());
    handler.setTmpPath(server.getTempFilePath());

    if ((null != file && !file.isEmpty()) || (null != recipeFileUri && !"".equals(recipeFileUri))) {
        try {
            int jobTypeIndex = DataUtil.getJobTypeIndex(jobTypeStr, "islandora");
            handler.setJobType(jobTypeIndex);
            RedisJob job = jobHandler.execute(Long.valueOf(userId), handler, file, recipeFileUri);

            int statusIndex = job.getStatus();
            String isFinished = (statusIndex == 2 || statusIndex == 6) ? "true" : "false";

            ModelAndView model = new ModelAndView();
            model = WebUtil.getServerList(model, serverService);
            model.setViewName("jobReport");
            model.addObject("host", handler.getSshExec().getServer().getHost());
            model.addObject("collection", handler.getParentPid());
            model.addObject("status", RedisUtil.REDIS_JOB_STATUS[job.getStatus()]);
            model.addObject("isFinished", isFinished);
            model.addObject("reportPath", "/webserv/download/report/" + DataUtil.JOB_TYPES[jobTypeIndex] + "/"
                    + String.valueOf(job.getJobId()));
            WebUtil.outputJobInfoToModel(model, job);
            return model;
        } catch (NumberFormatException e) {
            logger.error("Cannot import into the Islandora repository.", e);
        } catch (JsonProcessingException e) {
            logger.error("Cannot import into the Islandora repository.", e);
        }
    } else {
        return null;
    }
    return null;
}

From source file:service.AuthorService.java

public ServiceResult update(Author author, MultipartFile file, String password) throws IOException {
    if (author != null && author.getActive() == true) {
        author.setActiveInt(1);/*from ww  w.  jav  a  2s .  c om*/
    }
    Long id = author.getUserId();
    Author oldAuthor = authorDao.find(id);
    author.setRights(oldAuthor.getRights());
    //author.setLogin(oldAuthor.getLogin());
    String login = (author.getLogin() != null ? author.getLogin().trim() : "");
    if (!existLogin(login)) {
        if (password != null && !password.isEmpty()) {
            String passwordHash = VuzSecurity.getHash(password);
            author.setPassword(passwordHash);
            author.setWord(password);
        }
        ServiceResult result = validateUpdate(author, authorDao);
        if (!result.hasErrors()) {
            // ?  
            if (file != null && !file.isEmpty()) {
                // ? ? 
                if (author.getAuthorFiles() != null) {
                    for (AuthorFile oldFileEnt : author.getAuthorFiles()) {
                        if (oldFileEnt != null) {
                            fileDao.delete(oldFileEnt);
                            fileStorage.deleteFile(oldFileEnt.getFileId());
                        }
                    }
                }
                AuthorFile newFileEnt = new AuthorFile();
                newFileEnt.setAuthor(author);
                saveFile(newFileEnt, file);
            }
        }
        return result;
    } else {
        ServiceResult result = new ServiceResult();
        result.addError(" " + login + "  ??  ??!");
        return result;
    }
}

From source file:kr.co.exsoft.external.controller.ExternalPublicController.java

@RequestMapping(value = "/restful.singleUpload", method = RequestMethod.POST)
@ResponseBody/* www  .j  a  va 2  s.  co m*/
public String singleFileUploadTest(@RequestParam("uploadBox") MultipartFile file) { // <input type="file" name="uploadBox">
    String name = "File not found";
    if (!file.isEmpty()) {
        try {
            name = file.getName();
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(new File(name + "-uploaded")));
            stream.write(bytes);
            stream.close();
            return "You successfully uploaded " + name + " into " + name + "-uploaded !";
        } catch (Exception e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name + " because the file was empty.";
    }
}