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:org.openmrs.module.bannerprototype.web.controller.bannerprototypeManageController.java

@RequestMapping(value = "/module/bannerprototype/upload", method = RequestMethod.POST)
public @ResponseBody String handleFileUpload(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) throws IOException {

    String path = new ClassPathResource("taggers/").getURL().getPath();
    if (!file.isEmpty()) {
        try {/*from  www.ja  va  2 s .  com*/
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(path + name)));
            stream.write(bytes);
            stream.close();

            return "You successfully uploaded " + name + "!\n<a href=manage.form>back</a>";
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
            return "ERROR:  Please name your file";

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

From source file:net.nan21.dnet.core.web.controller.upload.FileUploadController.java

/**
 * Generic file upload. Expects an uploaded file and a handler alias to
 * delegate the uploaded file processing.
 * /* w ww  .  j  av  a 2  s  .  c  o m*/
 * @param handler
 *            spring bean alias of the
 *            {@link net.nan21.dnet.core.api.service.IFileUploadService}
 *            which should process the uploaded file
 * @param file
 *            Uploaded file
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/{handler}", method = RequestMethod.POST)
@ResponseBody
public String fileUpload(@PathVariable("handler") String handler, @RequestParam("file") MultipartFile file,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    if (logger.isInfoEnabled()) {
        logger.info("Processing file upload request with-handler {} ", new String[] { handler });
    }

    if (file.isEmpty()) {
        throw new Exception("Upload was not succesful. Try again please.");
    }

    this.prepareRequest(request, response);

    IFileUploadService srv = this.getFileUploadService(handler);
    Map<String, String> paramValues = new HashMap<String, String>();

    for (String p : srv.getParamNames()) {
        paramValues.put(p, request.getParameter(p));
    }

    IUploadedFileDescriptor fileDescriptor = new UploadedFileDescriptor();
    fileDescriptor.setContentType(file.getContentType());
    fileDescriptor.setOriginalName(file.getOriginalFilename());
    fileDescriptor.setNewName(file.getName());
    fileDescriptor.setSize(file.getSize());
    Map<String, Object> result = srv.execute(fileDescriptor, file.getInputStream(), paramValues);

    this.finishRequest();
    result.put("success", true);
    ObjectMapper mapper = getJsonMapper();
    return mapper.writeValueAsString(result);
}

From source file:org.shaf.server.controller.ActionApplicationController.java

/**
 * Deploys an application to the server.
 * /*from www  . ja va2s. co 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:org.pdfgal.pdfgalweb.services.impl.WatermarkServiceImpl.java

@Override
public DownloadForm putWatermark(final MultipartFile file, final String text, final CustomColor customColor,
        final Float alpha, final WatermarkPosition watermarkPosition, final String pages,
        final HttpServletResponse response) throws Exception {

    DownloadForm result = new DownloadForm();

    if (!file.isEmpty() && StringUtils.isNotBlank(text) && customColor != null && alpha != null
            && watermarkPosition != null && response != null) {

        final String originalName = file.getOriginalFilename();
        final String inputUri = this.fileUtils.saveFile(file);
        final String outputUri = this.fileUtils.getAutogeneratedName(originalName);

        // File is watermarked
        try {//from   w  ww  .ja va  2  s.c  o  m
            final List<Integer> pagesList = this.getPages(pages);
            this.pdfGal.putWatermark(inputUri, outputUri, text, customColor.getColor(), alpha,
                    watermarkPosition, pagesList);
        } catch (COSVisitorException | IOException | IllegalArgumentException e) {
            // Temporal files are deleted from system
            this.fileUtils.delete(inputUri);
            this.fileUtils.delete(outputUri);
            throw e;
        }

        // Temporal files are deleted from system
        this.fileUtils.delete(inputUri);

        result = new DownloadForm(outputUri, originalName);
    }

    return result;
}

From source file:org.chimi.s4s.controller.FileUploadController.java

@RequestMapping(value = "/upload/{serviceId}", method = RequestMethod.POST)
public String upload(@RequestParam(value = "file", required = false) MultipartFile userUploadFile,
        @PathVariable("serviceId") String serviceId, HttpServletRequest request, ModelMap model) {
    String resultViewName = "uploadResult";
    if (userUploadFile == null || userUploadFile.isEmpty()) {
        model.put(resultViewName, UploadResultResponse.createNoFileResult());
        return resultViewName;
    }/*from  www . j  ava2s .  com*/
    //  ? ?
    File tempFile = null;
    try {
        tempFile = getTemporaryFile(userUploadFile);
    } catch (Exception ex) {
        logger.error("fail to get temp file for " + userUploadFile.getOriginalFilename(), ex);
        model.put(resultViewName, UploadResultResponse.createErrorResult());
        return resultViewName;
    }
    //  ??   ? 
    try {
        String fileName = extractFileName(userUploadFile.getOriginalFilename());
        String mimeType = getMimeType(fileName);

        UploadResult uploadResult = saveTemporaryFileToFileService(userUploadFile, serviceId, fileName,
                mimeType, tempFile);

        String[] urls = createUrl(uploadResult, request);

        model.put(resultViewName, UploadResultResponse.createSuccessResult(uploadResult, urls[0], urls[1]));
        return resultViewName;
    } catch (Exception ex) {
        logger.error("fail to save file to storage" + userUploadFile.getOriginalFilename(), ex);
        model.put(resultViewName, UploadResultResponse.createErrorResult());
        return resultViewName;
    } finally {
        deleteTempFile(tempFile);
    }
}

From source file:org.openmrs.web.controller.observation.ObsFormController.java

/**
 * Sets the value of a complex obs from an http request.
 *
 * @param obs the complex obs whose value to set.
 * @param request the http request./*w w  w. j a va2s . c  o  m*/
 * @return the complex data input stream.
 */
private InputStream setComplexData(Obs obs, HttpServletRequest request) throws IOException {
    InputStream complexDataInputStream = null;

    if (request instanceof MultipartHttpServletRequest) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile complexDataFile = multipartRequest.getFile("complexDataFile");
        if (complexDataFile != null && !complexDataFile.isEmpty()) {
            complexDataInputStream = complexDataFile.getInputStream();

            ComplexData complexData = new ComplexData(complexDataFile.getOriginalFilename(),
                    complexDataInputStream);

            obs.setComplexData(complexData);
        }
    }

    return complexDataInputStream;
}

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   w  ww.  j  a  v a  2s  . com
    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:com.portal.controller.AdminController.java

@RequestMapping(value = "/employes/update", method = RequestMethod.POST)
public String submitUpdateEmployee(HttpServletRequest request, @RequestParam("id") int id,
        @ModelAttribute("employeedto") EmployeeDTO employeedto,
        @RequestParam(value = "avatarFile", required = false) MultipartFile avatar) throws Exception {

    //        Employee employee=new Employee();
    Employee employee = portalService.getEmployee(id);

    if (!avatar.isEmpty() && avatar.getContentType().equals("image/jpeg")) {
        portalService.saveFile(/*from   w  ww . j  a  va 2  s  . c o  m*/
                request.getServletContext().getRealPath("/template/img/") + "/" + avatar.getOriginalFilename(),
                avatar);
        employee.setAvatar(avatar.getOriginalFilename());
    }

    //        employee.setId(id);
    employee.setName(employeedto.getName());
    employee.setDepartment(portalService.getDepartment(employeedto.getDepartment()));
    employee.setPosition(portalService.getPosition(employeedto.getPosition()));
    employee.setPhone(employeedto.getPhone());
    employee.setEmail(employeedto.getEmail());
    employee.setDescription(employeedto.getDescription());
    portalService.saveEmployee(employee);

    return "redirect:/admin/employes";
}

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

@RequestMapping(value = { "/system/do/uploadfile", "/system/do/uploadfile/" }, method = RequestMethod.POST)
public @ResponseBody String uploadFileHandler(@RequestParam("file") MultipartFile file,
        @RequestParam("path") String path, HttpServletRequest request) {
    String name = file.getOriginalFilename();
    if (!file.isEmpty()) {
        try {/*  w  w w  .  j av a  2 s .  c om*/
            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 "";
        } 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:com.daphne.es.maintain.icon.web.controller.IconController.java

@RequestMapping(value = "{type}/create", method = RequestMethod.POST)
public String create(HttpServletRequest request, Model model,
        @RequestParam(value = "file", required = false) MultipartFile file,
        @Valid @ModelAttribute("m") Icon icon, BindingResult result, RedirectAttributes redirectAttributes) {

    if (file != null && !file.isEmpty()) {
        icon.setImgSrc(FileUploadUtils.upload(request, file, result));
    }/*from w  ww.  jav  a 2 s  . c o m*/
    String view = super.create(model, icon, result, redirectAttributes);
    genIconCssFile(request);
    return view;
}