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

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

Introduction

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

Prototype

@Override
InputStream getInputStream() throws IOException;

Source Link

Document

Return an InputStream to read the contents of the file from.

Usage

From source file:com.thoughtworks.go.server.controller.ArtifactsController.java

private boolean saveFile(int convertedAttempt, File artifact, MultipartFile multipartFile, boolean shouldUnzip)
        throws IOException {
    InputStream inputStream = null;
    boolean success;
    try {/*ww  w .  j  ava2 s .c om*/
        inputStream = multipartFile.getInputStream();
        success = artifactsService.saveFile(artifact, inputStream, shouldUnzip, convertedAttempt);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
    return success;
}

From source file:cn.orignzmn.shopkepper.common.utils.excel.ImportExcel.java

/**
 * /*  w w  w  .  j av  a  2  s .  c o m*/
 * @param file 
 * @param headerNum ???=?+1
 * @param sheetIndex ?
 * @throws InvalidFormatException 
 * @throws IOException 
 */
public ImportExcel(MultipartFile multipartFile, int headerNum, int sheetIndex)
        throws InvalidFormatException, IOException {
    this(multipartFile.getOriginalFilename(), multipartFile.getInputStream(), headerNum, sheetIndex);
}

From source file:org.openmrs.module.kenyaemr.page.controller.AdminSoftwareVersionPageController.java

public void controller(PageModel model,
        @RequestParam(value = "priorVersion", required = false) String priorVersion,
        HttpServletRequest request) {/*w  w w .  j  av  a 2 s  .co  m*/

    model.addAttribute("priorVersion", null);
    model.addAttribute("log", null);
    if (request instanceof MultipartHttpServletRequest) {
        MultipartFile uploaded = ((MultipartHttpServletRequest) request).getFile("distributionZip");
        if (uploaded != null) {
            // write this to a known file on disk, so we can use ZipFile, since ZipInputStream is buggy
            File file = null;
            try {
                file = File.createTempFile("distribution", ".zip");
                file.deleteOnExit();
                FileUtils.copyInputStreamToFile(uploaded.getInputStream(), file);

                List<String> log = Context.getService(ModuleDistroService.class).uploadDistro(file,
                        request.getSession().getServletContext());
                model.addAttribute("log", log);
                model.addAttribute("priorVersion", priorVersion);
            } catch (Exception ex) {
                StringWriter sw = new StringWriter();
                ex.printStackTrace(new PrintWriter(sw));
                model.addAttribute("log", Arrays.asList("Error", ex.getMessage(), sw.toString()));
            }
        }
    }
    String currentVersion = ModuleFactory.getModuleById("kenyaemr").getVersion();

    model.put("currentKenyaEmrVersion", currentVersion);
}

From source file:com.seer.datacruncher.spring.ValidateFilePopupController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String idSchema = request.getParameter("idSchema");
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("file");
    String resMsg = "";

    if (multipartFile.getOriginalFilename().endsWith(FileExtensionType.ZIP.getAbbreviation())) {
        // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one      
        ZipInputStream inStream = null;
        try {//from   ww w. jav  a  2  s .c  om
            inStream = new ZipInputStream(multipartFile.getInputStream());
            ZipEntry entry;
            while (!(isStreamClose(inStream)) && (entry = inStream.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    DatastreamsInput datastreamsInput = new DatastreamsInput();
                    datastreamsInput.setUploadedFileName(entry.getName());
                    byte[] byteInput = IOUtils.toByteArray(inStream);
                    resMsg += datastreamsInput.datastreamsInput(new String(byteInput), Long.parseLong(idSchema),
                            byteInput);
                }
                inStream.closeEntry();
            }
        } catch (IOException ex) {
            resMsg = "Error occured during fetch records from ZIP file.";
        } finally {
            if (inStream != null)
                inStream.close();
        }
    } else {
        // Case 1: When user upload a single file. In this cae just validate a single stream 
        String datastream = new String(multipartFile.getBytes());
        DatastreamsInput datastreamsInput = new DatastreamsInput();
        datastreamsInput.setUploadedFileName(multipartFile.getOriginalFilename());

        resMsg = datastreamsInput.datastreamsInput(datastream, Long.parseLong(idSchema),
                multipartFile.getBytes());

    }
    String msg = resMsg.replaceAll("'", "\"").replaceAll("\\n", " ");
    msg = msg.trim();
    response.setContentType("text/html");
    ServletOutputStream out = null;
    out = response.getOutputStream();
    out.write(("{success: " + true + " , message:'" + msg + "',   " + "}").getBytes());
    out.flush();
    out.close();
    return null;
}

From source file:gumga.framework.presentation.api.CSVGeneratorAPI.java

@ApiOperation(value = "csvuploadvalidate", notes = "Faz validao da importao via csv.")
@RequestMapping(method = RequestMethod.POST, value = "/csvuploadvalidate")
default SearchResult<String> csvUploadValidate(@RequestParam MultipartFile csv) throws IOException {
    int numeroLinha = 0;
    Class clazz = getGumgaService().clazz();
    InputStreamReader isr = new InputStreamReader(csv.getInputStream());
    BufferedReader bf = new BufferedReader(isr);
    String linha;/*from   www .  j ava 2s. c o  m*/
    String[] atributos = bf.readLine().split(CSV_SEPARATOR);
    numeroLinha++;
    Field idField = getIdField(clazz);
    Map<String, String> atributoValor = new HashMap<>();
    Map<String, Field> atributoField = new HashMap<>();
    for (String atributo : atributos) {
        atributoValor.put(atributo, null);
    }
    for (Field f : getAllAtributes(clazz)) {
        f.setAccessible(true);
        atributoField.put(f.getName(), f);
    }
    List<String> problemas = new ArrayList<>();
    while ((linha = bf.readLine()) != null) {
        numeroLinha++;
        String coluna = "";
        if (linha.trim().isEmpty()) {
            continue;
        }
        try {
            String[] valores = linha.split(CSV_SEPARATOR);
            for (int i = 0; i < valores.length; i++) {
                atributoValor.put(atributos[i], valores[i]);
            }
            Object entidade;
            String stringChave = atributoValor.get(idField.getName());
            if (stringChave != null && !stringChave.trim().isEmpty()) {
                entidade = getGumgaService().view(new Long(stringChave));
            } else {
                entidade = clazz.newInstance();
            }
            for (int i = 0; i < atributos.length; i++) {
                coluna = atributos[i];
                Field atributo = atributoField.get(coluna);
                if (coluna.equals(idField.getName())) {
                    continue;
                }
                if (coluna.equals("oi")) {
                    continue;
                }
                if (atributo.isAnnotationPresent(Version.class)) {
                    continue;
                }
                Class type = atributo.getType();
                String valorString = atributoValor.get(atributos[i]);
                if (valorString == null || valorString.trim().isEmpty()) {
                    continue;
                }
                if (GumgaModel.class.isAssignableFrom(type)) {
                    GumgaModel gm = (GumgaModel) atributo.get(entidade);
                    if (gm == null || !gm.getId().toString().equals(valorString)) {
                        Long valorLong = new Long(valorString);
                        Object entidadeAssociada = getGumgaService().genercView(type, valorLong);
                        atributo.set(entidade, entidadeAssociada);
                    }

                } else if (type.equals(Date.class)) {
                    Date valorDate = SDF.parse(valorString);
                    atributo.set(entidade, valorDate);
                } else {
                    Constructor constructorString = type.getConstructor(String.class);
                    Object valorAtributo = constructorString.newInstance(valorString);
                    atributo.set(entidade, valorAtributo);
                }
            }
            coluna = "ao salvar registro completo";
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | ParseException
                | NoSuchMethodException | SecurityException | InvocationTargetException ex) {
            problemas.add("Linha:" + numeroLinha + " Coluna:" + coluna + " Problema:" + ex);
        }
    }
    return new SearchResult<>(0, problemas.size(), problemas.size(), problemas);
}

From source file:gumga.framework.presentation.api.CSVGeneratorAPI.java

@Transactional
@ApiOperation(value = "csvupload", notes = "Faz importao via csv.")
@RequestMapping(method = RequestMethod.POST, value = "/csvupload")
default SearchResult<String> csvUpload(@RequestParam MultipartFile csv) throws IOException {
    int numeroLinha = 0;
    Class clazz = getGumgaService().clazz();
    InputStreamReader isr = new InputStreamReader(csv.getInputStream());
    BufferedReader bf = new BufferedReader(isr);
    String linha;//from   w w  w  . j  a  v a  2 s  .  c  om
    String[] atributos = bf.readLine().split(CSV_SEPARATOR);
    numeroLinha++;
    Field idField = getIdField(clazz);
    Map<String, String> atributoValor = new HashMap<>();
    Map<String, Field> atributoField = new HashMap<>();
    for (String atributo : atributos) {
        atributoValor.put(atributo, null);
    }
    for (Field f : getAllAtributes(clazz)) {
        f.setAccessible(true);
        atributoField.put(f.getName(), f);
    }
    List<String> problemas = new ArrayList<>();
    while ((linha = bf.readLine()) != null) {
        numeroLinha++;
        String coluna = "";
        if (linha.trim().isEmpty()) {
            continue;
        }
        try {
            String[] valores = linha.split(CSV_SEPARATOR);
            for (int i = 0; i < valores.length; i++) {
                atributoValor.put(atributos[i], valores[i]);
            }
            Object entidade;
            String stringChave = atributoValor.get(idField.getName());
            if (stringChave != null && !stringChave.trim().isEmpty()) {
                entidade = getGumgaService().view(new Long(stringChave));
            } else {
                entidade = clazz.newInstance();
            }
            for (int i = 0; i < atributos.length; i++) {
                coluna = atributos[i];
                Field atributo = atributoField.get(coluna);
                if (coluna.equals(idField.getName())) {
                    continue;
                }
                if (coluna.equals("oi")) {
                    continue;
                }
                if (atributo.isAnnotationPresent(Version.class)) {
                    continue;
                }
                Class type = atributo.getType();
                String valorString = atributoValor.get(atributos[i]);
                if (valorString == null || valorString.trim().isEmpty()) {
                    continue;
                }
                if (GumgaModel.class.isAssignableFrom(type)) {
                    GumgaModel gm = (GumgaModel) atributo.get(entidade);
                    if (gm == null || !gm.getId().toString().equals(valorString)) {
                        Long valorLong = new Long(valorString);
                        Object entidadeAssociada = getGumgaService().genercView(type, valorLong);
                        atributo.set(entidade, entidadeAssociada);
                    }

                } else if (type.equals(Date.class)) {
                    Date valorDate = SDF.parse(valorString);
                    atributo.set(entidade, valorDate);
                } else {
                    Constructor constructorString = type.getConstructor(String.class);
                    Object valorAtributo = constructorString.newInstance(valorString);
                    atributo.set(entidade, valorAtributo);
                }
            }
            coluna = "ao salvar registro completo";
            getGumgaService().save(entidade);
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | ParseException
                | NoSuchMethodException | SecurityException | InvocationTargetException ex) {
            problemas.add("Linha:" + numeroLinha + " Coluna:" + coluna + " Problema:" + ex);
        }
    }
    return new SearchResult<>(0, problemas.size(), problemas.size(), problemas);
}

From source file:com.devnexus.ting.web.controller.CallForPapersController.java

@RequestMapping(value = "/cfp", method = RequestMethod.POST)
public String addCfp(@Valid @ModelAttribute("cfpSubmission") CfpSubmissionForm cfpSubmission,
        BindingResult bindingResult, ModelMap model, HttpServletRequest request,
        RedirectAttributes redirectAttributes) {

    if (request.getParameter("cancel") != null) {
        return "redirect:/s/index";
    }//from w  w w .  j  a  v a 2  s. co m
    if (request.getParameter("addSpeaker") != null) {
        prepareReferenceData(model, request.isSecure());
        CfpSubmissionSpeaker speaker = new CfpSubmissionSpeaker();
        speaker.setCfpSubmission(cfpSubmission);
        cfpSubmission.getSpeakers().add(speaker);
        return "/cfp";
    }

    if (request.getParameter("removeSpeaker") != null) {
        prepareReferenceData(model, request.isSecure());
        cfpSubmission.getSpeakers().remove(Integer.valueOf(request.getParameter("removeSpeaker")).intValue());
        return "/cfp";
    }

    final String reCaptchaEnabled = environment.getProperty("recaptcha.enabled");
    final String recaptchaPrivateKey = environment.getProperty("recaptcha.privateKey");

    if (Boolean.valueOf(reCaptchaEnabled)) {
        String remoteAddr = request.getRemoteAddr();
        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
        reCaptcha.setPrivateKey(recaptchaPrivateKey);

        String challenge = request.getParameter("recaptcha_challenge_field");
        String uresponse = request.getParameter("recaptcha_response_field");
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

        if (!reCaptchaResponse.isValid()) {
            ObjectError error = new ObjectError("error", "Please insert the correct CAPTCHA.");
            bindingResult.addError(error);
            prepareReferenceData(model, request.isSecure());
            return "/cfp";
        }
    }

    if (bindingResult.hasErrors()) {
        prepareReferenceData(model, request.isSecure());
        return "/cfp";
    }

    final Event eventFromDb = businessService.getCurrentEvent();
    final CfpSubmission cfpSubmissionToSave = new CfpSubmission();

    if (cfpSubmission.getSpeakers().size() < 1) {
        ObjectError error = new ObjectError("error", "Please submit at least 1 speaker.");
        bindingResult.addError(error);
        prepareReferenceData(model, request.isSecure());
        return "/cfp";
    }

    if (cfpSubmission.getPictureFiles().size() != cfpSubmission.getSpeakers().size()) {
        ObjectError error = new ObjectError("error", "Please submit a picture for each speaker.");
        bindingResult.addError(error);
        prepareReferenceData(model, request.isSecure());
        return "/cfp";
    }

    cfpSubmissionToSave.setDescription(cfpSubmission.getDescription());
    cfpSubmissionToSave.setEvent(eventFromDb);

    cfpSubmissionToSave.setPresentationType(cfpSubmission.getPresentationType());
    cfpSubmissionToSave.setSessionRecordingApproved(cfpSubmission.isSessionRecordingApproved());
    cfpSubmissionToSave.setSkillLevel(cfpSubmission.getSkillLevel());
    cfpSubmissionToSave.setSlotPreference(cfpSubmission.getSlotPreference());
    cfpSubmissionToSave.setTitle(cfpSubmission.getTitle());
    cfpSubmissionToSave.setTopic(cfpSubmission.getTopic());

    int index = 0;
    for (CfpSubmissionSpeaker cfpSubmissionSpeaker : cfpSubmission.getSpeakers()) {

        final MultipartFile picture = cfpSubmission.getPictureFiles().get(index);
        InputStream pictureInputStream = null;

        try {
            pictureInputStream = picture.getInputStream();
        } catch (IOException e) {
            LOGGER.error("Error processing Image.", e);
            bindingResult.addError(new FieldError("cfpSubmission", "pictureFile", "Error processing Image."));
            prepareReferenceData(model, request.isSecure());
            return "/cfp";
        }

        if (pictureInputStream != null && picture.getSize() > 0) {
            SystemInformationUtils
                    .setSpeakerImage(
                            "CFP_" + cfpSubmissionSpeaker.getFirstName() + "_"
                                    + cfpSubmissionSpeaker.getLastName() + "_" + picture.getOriginalFilename(),
                            pictureInputStream);
        }

        index++;

        final CfpSubmissionSpeaker cfpSubmissionSpeakerToSave = new CfpSubmissionSpeaker();

        cfpSubmissionSpeakerToSave.setEmail(cfpSubmissionSpeaker.getEmail());
        cfpSubmissionSpeakerToSave.setBio(cfpSubmissionSpeaker.getBio());
        cfpSubmissionSpeakerToSave.setFirstName(cfpSubmissionSpeaker.getFirstName());
        cfpSubmissionSpeakerToSave.setGithubId(cfpSubmissionSpeaker.getGithubId());
        cfpSubmissionSpeakerToSave.setGooglePlusId(cfpSubmissionSpeaker.getGooglePlusId());
        cfpSubmissionSpeakerToSave.setLanyrdId(cfpSubmissionSpeaker.getLanyrdId());
        cfpSubmissionSpeakerToSave.setLastName(cfpSubmissionSpeaker.getLastName());
        cfpSubmissionSpeakerToSave.setLinkedInId(cfpSubmissionSpeaker.getLinkedInId());
        cfpSubmissionSpeakerToSave.setTwitterId(cfpSubmissionSpeaker.getTwitterId());
        cfpSubmissionSpeakerToSave.setLocation(cfpSubmissionSpeaker.getLocation());
        cfpSubmissionSpeakerToSave.setMustReimburseTravelCost(cfpSubmissionSpeaker.isMustReimburseTravelCost());
        cfpSubmissionSpeakerToSave.setTshirtSize(cfpSubmissionSpeaker.getTshirtSize());
        cfpSubmissionSpeakerToSave.setPhone(cfpSubmissionSpeaker.getPhone());
        cfpSubmissionSpeakerToSave.setCfpSubmission(cfpSubmissionToSave);
        cfpSubmissionToSave.getSpeakers().add(cfpSubmissionSpeakerToSave);

    }

    LOGGER.info(cfpSubmissionToSave.toString());
    businessService.saveAndNotifyCfpSubmission(cfpSubmissionToSave);

    return "redirect:/s/add-cfp-success";
}

From source file:com.baifendian.swordfish.webserver.service.storage.FileSystemStorageService.java

/**
 * ?, // w w w.jav a2  s .  c om
 *
 * @param file
 * @param destFilename
 */
@Override
public void store(MultipartFile file, String destFilename) {
    try {
        if (file.isEmpty()) {
            throw new StorageException("Failed to store empty file " + file.getOriginalFilename());
        }

        File destFile = new File(destFilename);
        File destDir = new File(destFile.getParent());

        if (!destDir.exists()) {
            FileUtils.forceMkdir(destDir);
        }

        Files.copy(file.getInputStream(), Paths.get(destFilename));
    } catch (IOException e) {
        throw new StorageException("Failed to store file " + file.getOriginalFilename(), e);
    }
}

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 {//from   w w  w. j a v  a 2s  .  c o 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:me.utils.excel.ImportExcelme.java

/**
 * //from   w  ww  .j  a va2s  . co m
 * @param file 
 * @param headerNum ???=?+1
 * @param sheetIndex ?
 * @throws InvalidFormatException 
 * @throws IOException 
 */
public ImportExcelme(MultipartFile multipartFile, int headerNum, int sheetIndex)
        throws InvalidFormatException, IOException {
    this(multipartFile.getOriginalFilename(), multipartFile.getInputStream(), headerNum, sheetIndex);
}