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.walmart.gatling.endpoint.v1.FileUploadController.java

@RequestMapping(method = RequestMethod.POST, value = "/upload")
public String handleFileUpload(@RequestParam("name") String name, @RequestParam("role") String role,
        @RequestParam("type") String type, @RequestParam("file") MultipartFile file,
        RedirectAttributes redirectAttributes) {

    if (!file.isEmpty()) {
        try {/*ww w .  ja  v  a  2s  .  co  m*/
            String path = tempFileDir + "/" + name;
            System.out.println(path);
            FileUtils.touch(new File(path));
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(path)));
            FileCopyUtils.copy(file.getInputStream(), stream);
            stream.close();
            Optional<String> trackingId = serverRepository.uploadFile(path, name, role, type);
            redirectAttributes.addFlashAttribute("message", "You successfully uploaded " + name + "! ");

            redirectAttributes.addFlashAttribute("link", "/#/file/" + trackingId.get());
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("message",
                    "You failed to upload " + name + " => " + e.getMessage());
        }
    } else {
        redirectAttributes.addFlashAttribute("message",
                "You failed to upload " + name + " because the file was empty");
    }

    return "redirect:upload";
}

From source file:com.opencart.controller.ProductController.java

@RequestMapping(value = "/product/upload", method = RequestMethod.POST)
public @ResponseBody ModelAndView handleFileUpload(@RequestParam("id") String id,
        @RequestParam("file") MultipartFile image, HttpServletRequest request) {
    if (!image.isEmpty()) {
        try {//from   www  .j  a  v  a2 s.c  o m
            File file = new File("c:/uploads/products/" + id + "/" + image.getOriginalFilename());

            FileUtils.writeByteArrayToFile(file, image.getBytes());
            Product product = productService.getById(Long.parseLong(id));
            product.setImg(file.getName());
            productService.update(product);

            List<Product> products = productService.list();
            ModelAndView mv = new ModelAndView("admin/product", "products", products);
            return mv;

        } catch (Exception e) {
            ModelAndView mv = new ModelAndView("admin/addProductImage");
            mv.addObject("id", id);
            return mv;
        }
    } else {
        ModelAndView mv = new ModelAndView("admin/addProductImage");
        mv.addObject("id", id);
        return mv;
    }
}

From source file:com.kalai.controller.FileUploadController.java

@RequestMapping(value = "/fileupload", method = RequestMethod.POST)
public @ResponseBody String fileuploadstore(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file, ModelMap map) {
    if (!file.isEmpty()) {
        try {//from  w  w w .  ja va  2s.c  om
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(name)));
            stream.write(bytes);
            stream.close();
            map.addAttribute("uploadoption", "uploaded");
            map.addAttribute("Status", "uploaded Successfully" + name);

        } catch (Exception e) {
            map.addAttribute("uploadoption", "uploaded");
            map.addAttribute("Status", "uploaded UnSuccessfully" + name);
        }
    } else {
        map.addAttribute("Status", "uploaded  is Empty" + name);
    }
    return "fileupload";
}

From source file:com.glaf.activiti.web.springmvc.ActivitiDeployController.java

/**
 * /*from  w  w w . ja va2s .c om*/
 * @param model
 * @param mFile
 * @return
 * @throws IOException
 */
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(Model model, @RequestParam("file") MultipartFile mFile) throws IOException {
    if (!mFile.isEmpty()) {
        String deploymentId = null;
        ProcessDefinition processDefinition = null;
        if (mFile.getOriginalFilename().endsWith(".zip") || mFile.getOriginalFilename().endsWith(".jar")) {
            ZipInputStream zipInputStream = null;
            try {
                zipInputStream = new ZipInputStream(mFile.getInputStream());
                deploymentId = activitiDeployService.addZipInputStream(zipInputStream).getId();
            } finally {
                IOUtils.closeStream(zipInputStream);
            }
        } else {
            String resourceName = FileUtils.getFilename(mFile.getOriginalFilename());
            deploymentId = activitiDeployService.addInputStream(resourceName, mFile.getInputStream()).getId();
        }
        if (StringUtils.isNotEmpty(deploymentId)) {
            logger.debug("deploymentId:" + deploymentId);
            processDefinition = activitiProcessQueryService.getProcessDefinitionByDeploymentId(deploymentId);
            if (processDefinition != null) {
                model.addAttribute("processDefinition", processDefinition);
                model.addAttribute("deploymentId", processDefinition.getDeploymentId());
                String resourceName = processDefinition.getDiagramResourceName();
                if (resourceName != null) {
                    ProcessUtils.saveProcessImageToFileSystem(processDefinition);
                    String path = "/deploy/bpmn/" + ProcessUtils.getImagePath(processDefinition);
                    model.addAttribute("path", path);
                    return "/activiti/deploy/showImage";
                }
            }
        }
    }

    String view = ViewProperties.getString("activiti.deploy");
    if (StringUtils.isNotEmpty(view)) {
        return view;
    }

    return "/activiti/deploy/deploy";
}

From source file:net.codejava.analyse.HomeController.java

/**
 * Controller method which respondes to a POST requst. It receives a MultipartFile, which in this case is a picture.
 * The controller writes the MultipartFile as an image to the disk. Afterwards it is executed with the analyse program.
 * After the analysis is performed the result is sent back to the client.
 * @throws InterruptedException /* w  w w . j  a v a 2 s .  c  o m*/
 */
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String handleFormUpload(@RequestParam("file") MultipartFile file)
        throws IOException, InterruptedException {
    Read r = new Read();
    if (!file.isEmpty()) {
        byte[] bytes = file.getBytes();//Put the bytes into a byte array
        FileOutputStream fos = new FileOutputStream("C:\\Users\\Martin\\Desktop\\IMG1.bmp");//A FileOutputStream with the path where the picture should be
        try {
            fos.write(bytes);//Writes the bytes to a file, in this case "creating" the picture as a .bmp
        } finally {
            fos.close();
            new CommandExecution("C:\\Users\\Martin\\SoftwareEng\\Analyse.bat");
        }
        Thread.sleep(3000);
        String result = r.reader("C:\\Users\\Martin\\Desktop\\Result.txt");
        return result;
    } else {
        return "doesn't work";//Returns this in case of empty file
    }
}

From source file:org.pdfgal.pdfgalweb.utils.impl.FileUtilsImpl.java

@Override
public String saveFile(final MultipartFile file) {

    String name = null;/*from   w  w w.j a  v a 2s .c  o  m*/

    if (!file.isEmpty()) {
        try {
            final String originalName = file.getOriginalFilename();
            name = this.getAutogeneratedName(originalName);
            final byte[] bytes = file.getBytes();
            final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(name)));
            stream.write(bytes);
            stream.close();
        } catch (final Exception e) {
            name = null;// TODO Incluir no log.
        }
    }

    return name;
}

From source file:org.openxdata.server.servlet.ImportServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from ww  w .  j av a  2 s.c om*/
        String importType = request.getParameter("type");
        String filecontents = null;

        CommonsMultipartResolver multipartResover = new CommonsMultipartResolver(/*this.getServletContext()*/);
        if (multipartResover.isMultipart(request)) {
            MultipartHttpServletRequest multipartRequest = multipartResover.resolveMultipart(request);
            MultipartFile uploadedFile = multipartRequest.getFile("filecontents");
            if (uploadedFile != null && !uploadedFile.isEmpty()) {
                filecontents = IOUtils.toString(uploadedFile.getInputStream());
            }
        }

        if (filecontents != null) {
            log.info("Starting import of type: " + importType);

            if (importType.equals("user")) {
                String errors = userService.importUsers(filecontents);
                if (errors != null) {
                    writeErrorsToResponse(errors, response);
                }
            } else {
                log.warn("Unknown import type: " + importType);
            }
        }
    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getOutputStream().print(ex.getMessage());
    }
}

From source file:controllers.CarPropertyController.java

@RequestMapping("/updateFromXml")
public String updateFromXml(Map<String, Object> model,
        @RequestParam(value = "xlsFile", required = false) MultipartFile file, RedirectAttributes ras) {
    if (file == null || file.isEmpty()) {
        ras.addFlashAttribute("error", "File not found");
    } else {//w  w  w.  jav  a 2s.c o  m
        File newFile = new File("/usr/local/etc/CarProperty");
        if (newFile.exists()) {
            newFile.delete();
        }
        try {
            FileUtils.writeByteArrayToFile(newFile, file.getBytes());
            carPropertyService.updateFromXml(newFile);
            ras.addFlashAttribute("error", carPropertyService.getResult().getErrors());
        } catch (Exception e) {
            ras.addFlashAttribute("error", "updateFromXml" + StringAdapter.getStackTraceException(e));
        }
        if (newFile.exists()) {
            newFile.delete();
        }
    }
    return "redirect:/CarProperty/show";
}

From source file:com.zte.gu.webtools.web.rfa.RfaController.java

@RequestMapping(method = RequestMethod.POST)
public ModelAndView scan(@RequestParam(required = true) MultipartFile ruFile, HttpSession session) {
    ModelAndView modelAndView = new ModelAndView("rfa/rfaScan");
    if (ruFile.isEmpty()) {
        modelAndView.getModelMap().addAttribute("error", "RU?");
    }// ww  w  .j ava 2  s . c  o  m
    if (!ACCEPT_TYPES.contains(ruFile.getContentType())) {
        modelAndView.getModelMap().addAttribute("error", "RU???");
    }

    InputStream ruInput = null;
    try {
        ruInput = ruFile.getInputStream();
        File tempZipFile = rfaService.exportXml(ruInput); //?
        if (tempZipFile != null) {
            session.setAttribute("filePath", tempZipFile.getPath());
            session.setAttribute("fileName", "rfa.zip");
            modelAndView.setViewName("redirect:/download");
        }
    } catch (Exception e) {
        LoggerFactory.getLogger(RfaController.class).warn("download error,", e);
        modelAndView.getModelMap().addAttribute("error", "?" + e.getMessage());
    } finally {
        IOUtils.closeQuietly(ruInput);
    }
    return modelAndView;
}

From source file:org.opentides.web.validator.ImageValidator.java

@Override
public void validate(Object obj, Errors errors) {
    AjaxUpload ajaxUpload = (AjaxUpload) obj;
    MultipartFile attachment = ajaxUpload.getAttachment();
    ValidationUtils.rejectIfEmpty(errors, "attachment", "photo.image-required");
    if (attachment != null && !attachment.isEmpty()) {
        String contentType = attachment.getContentType().substring(0, 6);
        if (!"image/".equals(contentType)) {
            errors.rejectValue("attachment", "photo.invalid-file-type",
                    "Invalid file. Profile Image must be in PNG, JPEG, GIF or BMP format.");
        } else if (attachment.getSize() > 1024 * 1024 * 10) {
            errors.rejectValue("attachment", "photo.invalid-file-size",
                    "Invalid file. Maximum file size is 10 Megabytes");
        }//from  w  w  w.  j  ava2  s  .co  m
    }

}