Example usage for org.springframework.web.multipart.commons CommonsMultipartFile getInputStream

List of usage examples for org.springframework.web.multipart.commons CommonsMultipartFile getInputStream

Introduction

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

Prototype

@Override
    public InputStream getInputStream() throws IOException 

Source Link

Usage

From source file:com.gelecekonline.web.UploadController.java

/**
 * API'ye Android uygulamasi tarafindan soyle erisilecektir: http://localhost:8080/uploadserver/api/upload
 * @param talep//from  w  w w  . j  a  v a  2s .c  o m
 * @param result
 * @param request
 * @return
 */
@RequestMapping("/api/upload")
@ResponseBody
public Yanit uploadGonder(Talep talep, BindingResult result, HttpServletRequest request) {

    Yanit yanit = null;
    try {
        /**
         * Istemci tarafindan gonderilen dosyanin da ayni isimde bir veri icermesi gerekiyor.Yani "dosya" ve "dosyaAdi" seklinde gonderilmelidir
         * dosyaAdi ile istemciden sunucuya Android cihazdaki dosya adini da gonderebiliyoruz. Bunun yaninda Talep nesnesine
         * baska parametreler ekleyerek cok sayida bilgi de gonderebiliriz
         */
        String dosyaAdi = talep.getDosyaAdi();
        CommonsMultipartFile dosya = talep.getDosya();
        if (dosya != null) {
            InputStream inputStream = dosya.getInputStream();
            File dizin = new File(DIZIN_ADI);
            if (!dizin.exists()) {
                System.out.println("dizin yoktu, olusturuluyor: " + DIZIN_ADI);
                boolean res = dizin.mkdir();
                if (res) {
                    System.out.println("dizin yaratildi");
                }

            }
            OutputStream out = new FileOutputStream(new File(DIZIN_ADI + "/" + dosyaAdi));
            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = inputStream.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            inputStream.close();
            out.flush();
            out.close();
            yanit = new Yanit();
            yanit.setYanitMesaji("Upload gerceklesti");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return yanit;

}

From source file:com.lohika.alp.reporter.fe.controller.LogController.java

@RequestMapping(method = RequestMethod.POST, value = "/results/test-method/{testMethodId}/log")
void saveLog(@PathVariable("testMethodId") long id, @ModelAttribute("uploadItem") UploadItem uploadItem,
        HttpServletResponse response) throws IOException {

    CommonsMultipartFile fileData = uploadItem.getFileData();

    // TODO Handle unexpected form data
    String name = fileData.getOriginalFilename();
    InputStream is = fileData.getInputStream();

    // If file extension is '.xml' or none save it as 'index.xml'
    if (name.toLowerCase().endsWith(".xml") || !name.matches(".*\\.\\w{1,3}$")) {

        logStorage.saveLog(id, "index.xml", is);

        // TODO TestMethod database creation should be performed with Spring
        // and REST web services, not from test listeners directly
        TestMethod testMethod = testMethodDAO.getTestMethod(id);

        // Set into DB that TestMethod has index log file
        testMethod.setHasLog(true);/*from w ww .  j  a va2s .com*/
        testMethodDAO.saveTestMethod(testMethod);
    } else {
        // Else save it with its original name

        logStorage.saveLog(id, name, is);
    }

    response.setStatus(HttpServletResponse.SC_CREATED);
    // TODO add log URL to response according REST principles
}

From source file:fr.putnami.pwt.plugin.spring.file.server.controller.FileTransfertController.java

@RequestMapping(value = "/file/upload/{uploadId}", method = RequestMethod.POST)
@ResponseBody//from   w  w  w.  j  ava 2  s  .co  m
public FileDto upload(@PathVariable String uploadId, @RequestParam("data") CommonsMultipartFile multipart,
        HttpServletRequest request, HttpServletResponse response) {
    OutputStream out = null;
    InputStream in = null;
    try {
        out = this.store.write(uploadId, multipart.getOriginalFilename(), multipart.getContentType());
        in = multipart.getInputStream();
        IOUtils.copy(in, out);
        return this.store.getFileBean(uploadId);
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

From source file:org.smigo.constraints.CommonsMultipartFileImageValidator.java

public boolean isValid(CommonsMultipartFile file, ConstraintValidatorContext constraintContext) {
    log.debug("Validating:" + file.getOriginalFilename() + " contenttype:" + file.getContentType()
            + " storagedescrip:" + file.getStorageDescription());
    if (file.isEmpty())
        return true;
    try {/*w ww .  j  av  a2 s  .  co  m*/
        BufferedImage image = ImageIO.read(file.getInputStream());
        if (image.getHeight() == height && image.getWidth() == width)
            return true;
    } catch (Exception e) {
        return false;
    }
    return false;
}

From source file:com.gradecak.alfresco.simpless.MetadataManager.java

/**
 * handles only simple types (no associations ... complex types)
 * /* ww w  .j av a2  s. c  o  m*/
 * any null properties will be removed from the node by calling nodeService.removeProperty, as
 * setting null is considered as a removal of the value
 * 
 * if a cm:content property is present than the value might be a file, a multipart, a ContentData
 * or a String. Otherwise the value must be <code>Serializable</code> However, before saving an
 * alfresco converter is executed on the vale for the given type repreented in the model
 * 
 * Any readonly properties will not be serialized/saved
 * 
 * return {@link SysBase} with converted values (did not check the repository) but without syncing
 * actions & aspects as we belongs to the same transaction and so the sync should be done after
 * the call to this method. As example we might consider behaviors that can change values of the
 * node
 */
public <T extends SysBase> T save(final T object) {
    Assert.notNull(object, "object must not be null");

    MetadataHolder holder = object.getMetadataHolder();
    Assert.notNull(holder, "the holder object must not be null");

    Map<QName, Serializable> allProps = holder.getPropertiesMap();

    // resolve unkown properties and put it all together
    Map<String, Serializable> unkwonProperties = object.getUnkwonProperties();
    for (Entry<String, Serializable> entry : unkwonProperties.entrySet()) {
        QName qname = QName.resolveToQName(serviceRegistry.getNamespaceService(), entry.getKey());
        allProps.put(qname, entry.getValue());
    }

    NodeRef toNode = object.getNodeRef();

    // works on latest alfresco versions. if
    // if (this.serviceRegistry.getCheckOutCheckInService().isCheckedOut(toNode)) {

    // works on all alfresco versions
    if (this.serviceRegistry.getCheckOutCheckInService().getWorkingCopy(toNode) != null) {
        if (LockStatus.LOCK_OWNER.equals(this.serviceRegistry.getLockService().getLockStatus(toNode))) {
            toNode = this.serviceRegistry.getCheckOutCheckInService().getWorkingCopy(toNode);
        }
    }

    Metadata properties = new Metadata();
    for (Entry<QName, Serializable> entry : allProps.entrySet()) {
        QName qname = entry.getKey();
        if (qname == null) {
            continue;
        }

        PropertyDefinition propertyDef = this.serviceRegistry.getDictionaryService().getProperty(qname);
        if (propertyDef == null) {
            continue;
        }

        if (holder.isReadOnlyProperty(qname)) {
            continue;
        }

        Serializable value = entry.getValue();

        if (value instanceof String[]) {
            // TODO: check if we need to handle props different than String[]
            value = ((String[]) value)[0];
        }

        DataTypeDefinition dataType = propertyDef.getDataType();
        if (DataTypeDefinition.CONTENT.equals(dataType.getName())) {

            if (toNode != null) {
                ContentWriter writer = this.serviceRegistry.getContentService().getWriter(toNode,
                        propertyDef.getName(), true);

                if (value instanceof CommonsMultipartFile) {
                    CommonsMultipartFile file = (CommonsMultipartFile) value;
                    writer.setMimetype(this.serviceRegistry.getMimetypeService()
                            .guessMimetype(file.getOriginalFilename()));
                    try {
                        writer.putContent(file.getInputStream());
                    } catch (IOException e) {
                        throw new ContentIOException("Could not write the file input stream", e);
                    }
                } else if (value instanceof File) {
                    File file = (File) value;
                    writer.setMimetype(this.serviceRegistry.getMimetypeService().guessMimetype(file.getName()));
                    writer.putContent(file);
                } else if (value instanceof String) {
                    writer.setMimetype("text/plain");
                    writer.putContent((String) value);
                } else if (value instanceof ContentData) {
                    properties.put(qname, (ContentData) value);
                } else {
                    if (value != null) {
                        throw new RuntimeException(
                                "Unhandled property of type d:content. Name : " + propertyDef.getName());
                    }
                }
            }
        } else {
            if (DataTypeDefinition.QNAME.equals(dataType.getName())) {
                if (value instanceof String && !StringUtils.hasText((String) value)) {
                    continue;
                }
            }

            Object convertedValue = converter.convert(dataType, value);
            if (convertedValue == null) {
                // TODO marked in order to verify this behavior
                // we remove the specific property as its value has been erased
                this.serviceRegistry.getNodeService().removeProperty(toNode, qname);
            } else {
                properties.put(qname, (Serializable) convertedValue);
                object.getMetadataHolder().setProperty(qname, (Serializable) convertedValue);
            }
        }
    }

    // assure to remove nodeRef property before saving
    properties.remove(ContentModel.PROP_NODE_REF);
    if (!properties.isEmpty()) {
        this.serviceRegistry.getNodeService().addProperties(toNode, properties);
    }

    syncAspectsAndActions(toNode, object);

    return object;
}

From source file:alpha.portal.webapp.controller.FileUploadController.java

/**
 * On submit.// www  . j  a  v  a 2  s  .co  m
 * 
 * @param fileUpload
 *            the file upload
 * @param errors
 *            the errors
 * @param request
 *            the request
 * @return the string
 * @throws Exception
 *             the exception
 */
@RequestMapping(method = RequestMethod.POST)
public String onSubmit(final FileUpload fileUpload, final BindingResult errors,
        final HttpServletRequest request) throws Exception {

    if (request.getParameter("cancel") != null)
        return this.getCancelView();

    if (this.validator != null) { // validator is null during testing
        this.validator.validate(fileUpload, errors);

        if (errors.hasErrors())
            return "fileupload";
    }

    // validate a file was entered
    if (fileUpload.getFile().length == 0) {
        final Object[] args = new Object[] { this.getText("uploadForm.file", request.getLocale()) };
        errors.rejectValue("file", "errors.required", args, "File");

        return "fileupload";
    }

    final MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    final CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");

    // the directory to upload to
    final String uploadDir = this.getServletContext().getRealPath("/resources") + "/" + request.getRemoteUser()
            + "/";

    // Create the directory if it doesn't exist
    final File dirPath = new File(uploadDir);

    if (!dirPath.exists()) {
        dirPath.mkdirs();
    }

    // retrieve the file data
    final InputStream stream = file.getInputStream();

    // write the file to the file specified
    final OutputStream bos = new FileOutputStream(uploadDir + file.getOriginalFilename());
    int bytesRead;
    final byte[] buffer = new byte[8192];

    while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
        bos.write(buffer, 0, bytesRead);
    }

    bos.close();

    // close the stream
    stream.close();

    // place the data into the request for retrieval on next page
    request.setAttribute("friendlyName", fileUpload.getName());
    request.setAttribute("fileName", file.getOriginalFilename());
    request.setAttribute("contentType", file.getContentType());
    request.setAttribute("size", file.getSize() + " bytes");
    request.setAttribute("location",
            dirPath.getAbsolutePath() + Constants.FILE_SEP + file.getOriginalFilename());

    final String link = request.getContextPath() + "/resources" + "/" + request.getRemoteUser() + "/";
    request.setAttribute("link", link + file.getOriginalFilename());

    return this.getSuccessView();
}

From source file:es.ucm.fdi.dalgs.activity.service.ActivityService.java

@PreAuthorize("hasPermission(#course, 'WRITE') or hasRole('ROLE_ADMIN')")
@Transactional(readOnly = false)/*  w  ww  .j  av a2 s  .  c o m*/
public void addAttachmentToCourseActivity(Course course, FileUpload fileupload, Long id_activity,
        Long id_course, Long id_academic) throws IOException {

    Activity act = getActivity(id_activity, id_course, null, id_academic).getSingleElement();
    Attachment attach = new Attachment();
    CommonsMultipartFile file = fileupload.getFilepath();
    String key = getStorageKey(id_activity);
    String mimeType = file.getContentType();
    storageManager.putObject(bucket, key, mimeType, file.getInputStream());

    if (act.getAttachments() == null)
        act.setAttachments(new ArrayList<Attachment>());

    String aaa = storageManager.getUrl(bucket, key).toExternalForm();
    attach.setFile(aaa);
    attach.setDescription(fileupload.getDescription());
    attach.setName(fileupload.getName());
    act.getAttachments().add(attach);
    repositoryActivity.saveActivity(act);

}

From source file:es.ucm.fdi.dalgs.activity.service.ActivityService.java

@PreAuthorize("hasPermission(#course, 'WRITE') or hasPermission(#group, 'ADMINISTRATION') or hasRole('ROLE_ADMIN')")
@Transactional(readOnly = false)//from w  w w  .  j  a  v a  2  s.  c o m
public void addAttachmentToGroupActivity(Course course, Group group, FileUpload fileupload, Long id_group,
        Long id_course, Long id_activity, Long id_academic) throws IOException {

    Attachment attach = new Attachment();
    Activity act = getActivity(id_activity, id_course, id_group, id_academic).getSingleElement();

    CommonsMultipartFile file = fileupload.getFilepath();

    String key = getStorageKey(id_activity);
    String mimeType = file.getContentType();
    storageManager.putObject(bucket, key, mimeType, file.getInputStream());
    if (act.getAttachments() == null)
        act.setAttachments(new ArrayList<Attachment>());
    String aaa = storageManager.getUrl(bucket, key).toExternalForm();
    attach.setFile(aaa);
    attach.setDescription(fileupload.getDescription());
    attach.setName(fileupload.getName());
    act.getAttachments().add(attach);
    repositoryActivity.saveActivity(act);

}

From source file:org.openmrs.module.report.web.controller.report.ReportTypeController.java

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(@ModelAttribute("reportType") BirtReportType reportType, BindingResult bindingResult,
        HttpServletRequest request, SessionStatus status) {
    new BirtReportTypeValidator().validate(reportType, bindingResult);
    if (bindingResult.hasErrors()) {
        return "/module/report/report/reportType";
    } else {//from   ww w.j  av a 2s .c  om
        BirtReportService birtReportService = Context.getService(BirtReportService.class);
        BirtReportConfig config = ReportConstants.getConfig();
        String tempPath = config.getRealPath();
        if (StringUtils.isBlank(tempPath)) {
            Throwable th = new Throwable("Not exist realpath for save file report!");

        }
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("reportFile");
        if (file != null && file.getBytes() != null && file.isEmpty() == false) {
            long temp = new Date().getTime();
            //String nameReport = org.openmrs.module.report.util.StringUtils.replaceSpecialWithUnderLineCharacter(reportType.getBirtReport().getName());
            //String nameReportType = org.openmrs.module.report.util.StringUtils.replaceSpecialWithUnderLineCharacter(reportType.getName());
            String fileName = reportType.getBirtReport().getId() + "_" + temp + ".rptdesign";
            String reportFilename = tempPath + "/" + fileName;
            reportFilename = reportFilename.replaceAll("//", "/");

            try {
                FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(reportFilename));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            reportType.setPath(fileName);
        } else if (reportType.getId() != null && reportType.getId().intValue() > 0) {
            reportType.setPath(birtReportService.getBirtReportTypeById(reportType.getId()).getPath());
        }

        reportType.setCreatedBy(Context.getAuthenticatedUser().getGivenName());
        reportType.setCreatedOn(new Date());
        birtReportService.saveBirtReportType(reportType);
        status.setComplete();
        return "redirect:/module/report/reportType.form?reportId=" + reportType.getBirtReport().getId();
    }
}

From source file:com.jeans.iservlet.controller.impl.ImportController.java

@RequestMapping(method = RequestMethod.POST, value = "/ac")
@ResponseBody/*from www .j  a va  2s  . c  om*/
public void importAC(@RequestParam("data") CommonsMultipartFile data, HttpServletResponse response)
        throws IOException {
    PrintWriter out = response.getWriter();
    if (null == data) {
        showError(out, "??");
        out.close();
        return;
    }
    int count = 0;
    String info = null;
    try (Workbook workBook = WorkbookFactory.create(data.getInputStream())) {
        Sheet acsSheet = workBook.getSheet("");
        if (null == acsSheet) {
            data.getInputStream().close();
            showError(out, "????Sheet");
            out.close();
            return;
        }
        Company comp = getCurrentCompany();
        int total = acsSheet.getLastRowNum();
        double progress = 0.0;
        double step = 100.0 / (double) total;
        showProgressDialog(out, getCurrentCompany().getAlias() + "???");
        // acsSheet: 1?06?70?
        int last = acsSheet.getLastRowNum();
        for (int rn = 1; rn <= last; rn++) {
            Row r = acsSheet.getRow(rn);
            // ??""???
            String flag = StringUtils
                    .trim(ExcelUtils.getCellValueAsString(r.getCell(0, Row.RETURN_BLANK_AS_NULL)));
            // ???name?
            String name = StringUtils
                    .trim(ExcelUtils.getCellValueAsString(r.getCell(2, Row.RETURN_BLANK_AS_NULL)));
            progress += step;
            if (!"".equals(flag) || StringUtils.isBlank(name)) {
                continue;
            }
            showProgress(out, "???" + name, progress); // 
            AccessoryType type = parseAccessoryType(
                    StringUtils.trim(ExcelUtils.getCellValueAsString(r.getCell(1, Row.RETURN_BLANK_AS_NULL))));
            String brand = StringUtils
                    .trim(ExcelUtils.getCellValueAsString(r.getCell(3, Row.RETURN_BLANK_AS_NULL)));
            String model = StringUtils
                    .trim(ExcelUtils.getCellValueAsString(r.getCell(4, Row.RETURN_BLANK_AS_NULL)));
            String description = StringUtils
                    .trim(ExcelUtils.getCellValueAsString(r.getCell(5, Row.RETURN_BLANK_AS_NULL)));
            String unit = StringUtils
                    .trim(ExcelUtils.getCellValueAsString(r.getCell(6, Row.RETURN_BLANK_AS_NULL)));

            if (null != acsService.create(comp, type, name, brand, model, unit, description)) {
                count++;
            }
        }
        info = "????" + count + "?";
    } catch (Exception e) {
        log(e);
        info = "???????"
                + count + "?";
    } finally {
        data.getInputStream().close();
        closeProgressDialog(out);
        showInfo(out, info);
        out.close();
        log(info);
    }
}