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.dlshouwen.wzgl.picture.controller.PictureController.java

/**
 * //from w  w  w .  j  a v a  2  s . c o  m
 *
 * @param picture 
 * @param bindingResult ?
 * @param request 
 * @return ajax?
 */
@RequestMapping(value = "/{albumId}/ajaxMultipartAdd", method = RequestMethod.POST)
public void ajaxAddMultipartPictureAl(@Valid Picture picture, BindingResult bindingResult,
        HttpServletRequest request, HttpServletResponse response, @PathVariable String albumId)
        throws Exception {
    //      AJAX?
    AjaxResponse ajaxResponse = new AjaxResponse();
    String flag = request.getParameter("flag");
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("file");
    String sname = multipartFile.getOriginalFilename();
    //?
    String path = null;
    if (null != multipartFile && StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) {
        JSONObject jobj = FileUploadClient.upFile(request, multipartFile.getOriginalFilename(),
                multipartFile.getInputStream());
        if (jobj.getString("responseMessage").equals("OK")) {
            path = jobj.getString("fpath");
        }
    }

    /*
     String fileName = multipartFile.getOriginalFilename();
     int pos = fileName.lastIndexOf(".");
     fileName = fileName.substring(pos);
     String fileDirPath = request.getSession().getServletContext().getRealPath("/");
     String path = fileDirPath.substring(0, fileDirPath.lastIndexOf(File.separator)) + CONFIG.UPLOAD_PIC_PATH;
     Date date = new Date();
     fileName = String.valueOf(date.getTime()) + fileName;
     File file = new File(path);
     if (!file.exists()) {
     file.mkdirs();
     }
     file = new File(path + "/" + fileName);
     if (!file.exists()) {
     file.createNewFile();
     }
     path = path + "/" + fileName;
     FileOutputStream fos = null;
     InputStream s = null;
     try {
     fos = new FileOutputStream(file);
     s = multipartFile.getInputStream();
     byte[] buffer = new byte[1024];
     int read = 0;
     while ((read = s.read(buffer)) != -1) {
     fos.write(buffer, 0, read);
     }
     fos.flush();
     } catch (Exception e) {
     e.printStackTrace();
     } finally {
     if (fos != null) {
     fos.close();
     }
     if (s != null) {
     s.close();
     }
     }
     */
    if (StringUtils.isNotEmpty(path)) {
        //       ????
        SessionUser sessionUser = (SessionUser) request.getSession().getAttribute(CONFIG.SESSION_USER);
        String userId = sessionUser.getUser_id();
        String userName = sessionUser.getUser_name();
        Date nowDate = new Date();

        //      ??
        picture.setPicture_name(sname);
        //       ?   
        picture.setPicture_id(new GUID().toString());
        picture.setCreate_time(nowDate);
        picture.setUser_id(userId);
        picture.setUser_name(userName);
        path = path.replaceAll("\\\\", "/");
        picture.setPath(path);
        picture.setAlbum_id(albumId);
        picture.setFlag("1");
        picture.setShow("1");
        picture.setUpdate_time(new Date());

        //       
        dao.insertPicture(picture);

        //??
        if (flag.equals("article")) {
            Album alb = albumDao.getAlbumById(albumId);
            if (StringUtils.isEmpty(alb.getAlbum_coverpath())) {
                albumDao.setAlbCover(albumId, picture.getPath());
            }
        }

        //       ????
        ajaxResponse.setSuccess(true);
        ajaxResponse.setSuccessMessage("??");
    } else {
        //       ????
        ajaxResponse.setError(true);
        ajaxResponse.setErrorMessage("?");
    }

    //      ?
    LogUtils.updateOperationLog(request, OperationType.INSERT,
            "?" + picture.getPicture_id());

    response.setContentType("text/html;charset=utf-8");
    JSONObject obj = JSONObject.fromObject(ajaxResponse);
    response.getWriter().write(obj.toString());
    return;
}

From source file:architecture.ee.web.spring.controller.SecureWebMgmtDataController.java

@RequestMapping(value = "/mgmt/logo/upload.json", method = RequestMethod.POST)
@ResponseBody/* w w  w .  j av a 2 s. c  om*/
public Result uploadLogoImage(
        @RequestParam(value = "objectType", defaultValue = "1", required = false) Integer objectType,
        @RequestParam(value = "objectId", defaultValue = "0", required = false) Long objectId,
        MultipartHttpServletRequest request) throws NotFoundException, IOException {

    User user = SecurityHelper.getUser();
    if (objectId == 0) {
        if (objectType == 1) {
            objectId = user.getCompanyId();
        } else if (objectType == 30) {
            objectId = WebSiteUtils.getWebSite(request).getWebSiteId();
        }
    }
    Iterator<String> names = request.getFileNames();
    while (names.hasNext()) {
        String fileName = names.next();
        log.debug(fileName);
        MultipartFile mpf = request.getFile(fileName);
        InputStream is = mpf.getInputStream();
        log.debug("file name: " + mpf.getOriginalFilename());
        log.debug("file size: " + mpf.getSize());
        log.debug("file type: " + mpf.getContentType());
        log.debug("file class: " + is.getClass().getName());

        LogoImage logo = logoManager.createLogoImage();
        logo.setFilename(mpf.getName());
        logo.setImageContentType(mpf.getContentType());
        logo.setImageSize((int) mpf.getSize());
        logo.setObjectType(objectType);
        logo.setObjectId(objectId);
        logo.setPrimary(true);

        logoManager.addLogoImage(logo, mpf.getInputStream());
    }
    return Result.newResult();
}

From source file:business.services.FileService.java

public File uploadPart(User user, String name, File.AttachmentType type, MultipartFile file, Integer chunk,
        Integer chunks, String flowIdentifier) {
    try {//from w  w w  . j  a v a 2 s.com
        String identifier = user.getId().toString() + "_" + flowIdentifier;
        String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        log.info("File content-type: " + file.getContentType());
        try {
            contentType = MediaType.valueOf(file.getContentType()).toString();
            log.info("Media type: " + contentType);
        } catch (InvalidMediaTypeException e) {
            log.warn("Invalid content type: " + e.getMediaType());
            //throw new FileUploadError("Invalid content type: " + e.getMediaType());
        }
        InputStream input = file.getInputStream();

        // Create temporary file for chunk
        Path path = fileSystem.getPath(uploadPath).normalize();
        if (!path.toFile().exists()) {
            Files.createDirectory(path);
        }
        name = URLEncoder.encode(name, "utf-8");

        String prefix = getBasename(name);
        String suffix = getExtension(name);
        Path f = Files.createTempFile(path, prefix, suffix + "." + chunk + ".chunk").normalize();
        // filter path names that point to places outside the upload path.
        // E.g., to prevent that in cases where clients use '../' in the filename
        // arbitrary locations are reachable.
        if (!Files.isSameFile(path, f.getParent())) {
            // Path f is not in the upload path. Maybe 'name' contains '..'?
            throw new FileUploadError("Invalid file name");
        }
        log.info("Copying file to " + f.toString());

        // Copy chunk to temporary file
        Files.copy(input, f, StandardCopyOption.REPLACE_EXISTING);

        // Save chunk location in chunk map
        SortedMap<Integer, Path> chunkMap;
        synchronized (uploadChunks) {
            // FIXME: perhaps use a better identifier? Not sure if this one 
            // is unique enough...
            chunkMap = uploadChunks.get(identifier);
            if (chunkMap == null) {
                chunkMap = new TreeMap<Integer, Path>();
                uploadChunks.put(identifier, chunkMap);
            }
        }
        chunkMap.put(chunk, f);
        log.info("Chunk " + chunk + " saved to " + f.toString());

        // Assemble complete file if all chunks have been received
        if (chunkMap.size() == chunks.intValue()) {
            uploadChunks.remove(identifier);
            Path assembly = Files.createTempFile(path, prefix, suffix).normalize();
            // filter path names that point to places outside the upload path.
            // E.g., to prevent that in cases where clients use '../' in the filename
            // arbitrary locations are reachable.
            if (!Files.isSameFile(path, assembly.getParent())) {
                // Path assembly is not in the upload path. Maybe 'name' contains '..'?
                throw new FileUploadError("Invalid file name");
            }
            log.info("Assembling file " + assembly.toString() + " from " + chunks + " chunks...");
            OutputStream out = Files.newOutputStream(assembly, StandardOpenOption.CREATE,
                    StandardOpenOption.APPEND);

            // Copy chunks to assembly file, delete chunk files
            for (int i = 1; i <= chunks; i++) {
                //log.info("Copying chunk " + i + "...");
                Path source = chunkMap.get(new Integer(i));
                if (source == null) {
                    log.error("Cannot find chunk " + i);
                    throw new FileUploadError("Cannot find chunk " + i);
                }
                Files.copy(source, out);
                Files.delete(source);
            }

            // Save assembled file name to database
            log.info("Saving attachment to database...");
            File attachment = new File();
            attachment.setName(URLDecoder.decode(name, "utf-8"));
            attachment.setType(type);
            attachment.setMimeType(contentType);
            attachment.setDate(new Date());
            attachment.setUploader(user);
            attachment.setFilename(assembly.getFileName().toString());
            attachment = fileRepository.save(attachment);
            return attachment;
        }
        return null;
    } catch (IOException e) {
        log.error(e);
        throw new FileUploadError(e.getMessage());
    }
}

From source file:com.epam.ta.reportportal.ws.controller.impl.LogController.java

@Override
@RequestMapping(method = RequestMethod.POST, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
@ResponseBody/* w  ww  .j  a  v  a2 s.  co m*/
// @ApiOperation("Create log (batching operation)")
// Specific handler should be added for springfox in case of similar POST
// request mappings
@ApiIgnore
public ResponseEntity<BatchSaveOperatingRS> createLog(@PathVariable String projectName,
        @RequestPart(value = Constants.LOG_REQUEST_JSON_PART) SaveLogRQ[] createLogRQs,
        HttpServletRequest request, Principal principal) {

    String prjName = EntityUtils.normalizeProjectName(projectName);
    /*
     * Since this is multipart request we can retrieve list of uploaded
    * files
    */
    Map<String, MultipartFile> uploadedFiles = getUploadedFiles(request);
    BatchSaveOperatingRS response = new BatchSaveOperatingRS();
    EntryCreatedRS responseItem;
    /* Go through all provided save log request items */
    for (SaveLogRQ createLogRq : createLogRQs) {
        try {
            validateSaveRQ(createLogRq);
            String filename = createLogRq.getFile() == null ? null : createLogRq.getFile().getName();
            if (StringUtils.isEmpty(filename)) {
                /*
                 * There is no filename in request. Use simple save
                 * method
                 */
                responseItem = createLog(prjName, createLogRq, principal);

            } else {
                /* Find by request part */
                MultipartFile data = findByFileName(filename, uploadedFiles);
                BusinessRule.expect(data, Predicates.notNull()).verify(ErrorType.BINARY_DATA_CANNOT_BE_SAVED,
                        Suppliers.formattedSupplier("There is no request part or file with name {}", filename));
                /*
                 * If provided content type is null or this is octet
                 * stream, try to detect real content type of binary
                 * data
                 */
                if (!StringUtils.isEmpty(data.getContentType())
                        && !MediaType.APPLICATION_OCTET_STREAM_VALUE.equals(data.getContentType())) {
                    responseItem = createLogMessageHandler.createLog(createLogRq,
                            new BinaryData(data.getContentType(), data.getSize(), data.getInputStream()),
                            data.getOriginalFilename(), prjName);
                } else {
                    byte[] consumedData = IOUtils.toByteArray(data.getInputStream());
                    responseItem = createLogMessageHandler.createLog(createLogRq,
                            new BinaryData(contentTypeResolver.detectContentType(consumedData), data.getSize(),
                                    new ByteArrayInputStream(consumedData)),
                            data.getOriginalFilename(), prjName);

                }
            }
            response.addResponse(new BatchElementCreatedRS(responseItem.getId()));
        } catch (Exception e) {
            response.addResponse(
                    new BatchElementCreatedRS(ExceptionUtils.getStackTrace(e), ExceptionUtils.getMessage(e)));
        }
    }
    return new ResponseEntity<>(response, HttpStatus.CREATED);
}

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

/**
 * Puts data to the server.//from   ww  w  .j  a v  a2 s  . co m
 * 
 * @param storage
 *            the storage type.
 * @param alias
 *            the data alias.
 * @param data
 *            the data to upload.
 * @throws NetworkContentException
 * @throws Exception
 *             if an error occurs.
 */
@RequestMapping(value = "/upload/{storage}/{alias}", method = RequestMethod.POST)
public void onUpload(@PathVariable String storage, @PathVariable String alias, @RequestBody MultipartFile data)
        throws Exception {
    LOG.debug("CALL service: /cmd/upload/{" + storage + "}/{" + alias + "} with attached data.");
    LOG.trace("The attached data: " + data);

    if (data.isEmpty()) {
        LOG.warn("There no providing data.");
    } else {
        Firewall firewall = super.getFirewall();
        String username = super.getUserName();
        StorageDriver driver = OPER.getStorageDriver(firewall, username, StorageType.PROVIDER, storage);

        LOG.trace("Driver for uploading: " + driver);
        LOG.trace("Uploading data name: " + data.getName());
        LOG.trace("Uploading data size: " + data.getSize());

        try (InputStream in = data.getInputStream(); OutputStream out = driver.getOutputStream(alias)) {
            ByteStreams.copy(in, out);
        } catch (IOException exc) {
            throw exc;
        }
    }
}

From source file:com.github.zhanhb.ckfinder.connector.handlers.command.FileUploadCommand.java

/**
 * saves temporary file in the correct file path.
 *
 * @param path path to save file//from   w  w w.  j  a v  a  2s.co m
 * @param item file upload item
 * @param param the parameter
 * @param context ckfinder context
 * @throws IOException when IO Exception occurs.
 * @throws ConnectorException when error occurs
 */
private void saveTemporaryFile(Path path, MultipartFile item, FileUploadParameter param,
        CKFinderContext context) throws IOException, ConnectorException {
    Path file = getPath(path, param.getNewFileName());

    if (ImageUtils.isImageExtension(file)) {
        if (!context.isCheckSizeAfterScaling() && !ImageUtils.checkImageSize(item, context)) {
            param.throwException(ErrorCode.UPLOADED_TOO_BIG);
        }
        ImageUtils.createTmpThumb(item, file, getFileItemName(item), context);
        if (context.isCheckSizeAfterScaling()
                && !FileUtils.isFileSizeInRange(param.getType(), Files.size(file))) {
            Files.deleteIfExists(file);
            param.throwException(ErrorCode.UPLOADED_TOO_BIG);
        }
    } else {
        try (InputStream in = item.getInputStream()) {
            Files.copy(in, file);
        }
    }
    FileUploadEvent args = new FileUploadEvent(param.getCurrentFolder(), file);
    context.fireOnFileUpload(args);
}

From source file:cn.lhfei.fu.service.impl.HomeworkBaseServiceImpl.java

/**
 *  //from  w ww.j a v  a  2 s.c om
 * 
 * @see cn.lhfei.fu.service.HomeworkBaseService#update(cn.lhfei.fu.web.model.HomeworkBaseModel)
 */
@Override
public boolean update(HomeworkBaseModel model, String userType) throws NullPointerException {
    OutputStream out = null;
    BufferedOutputStream bf = null;
    Date currentTime = new Date();

    List<MultipartFile> files = model.getFiles();
    try {
        HomeworkBase base = homeworkBaseDAO.find(model.getBaseId());

        base.setModifyTime(currentTime);
        base.setActionType("" + OperationTypeEnum.SC.getCode());
        base.setOperationTime(currentTime);

        homeworkBaseDAO.save(base); // update homework_base info

        int num = 1;
        for (MultipartFile file : files) {// save archive file

            if (file.getSize() > 0) {
                String filePath = filePathBuilder.buildFullPath(model, model.getStudentName());
                String fileName = filePathBuilder.buildFileName(model, model.getStudentName(), num);

                String[] names = file.getOriginalFilename().split("[.]");

                String fileType = names[names.length - 1];

                String fullPath = filePath + File.separator + fileName + "." + fileType;

                out = new FileOutputStream(new File(fullPath));

                bf = new BufferedOutputStream(out);

                IOUtils.copyLarge(file.getInputStream(), bf);

                HomeworkArchive archive = new HomeworkArchive();
                archive.setArchiveName(fileName);
                archive.setArchivePath(fullPath);
                archive.setCreateTime(currentTime);
                archive.setModifyTime(currentTime);
                archive.setName(model.getName());
                archive.setStudentBaseId(model.getStudentBaseId());
                archive.setHomeworkBaseId(model.getBaseId());
                /*archive.setHomeworkBase(base);*/
                archive.setStudentName(model.getStudentName());
                archive.setStudentId(model.getStudentId());

                // ?
                if (userType != null && userType.equals(UserTypeEnum.STUDENT.getCode())) {
                    archive.setStatus("" + ApproveStatusEnum.DSH.getCode());
                } else if (userType != null && userType.equals(UserTypeEnum.TEACHER.getCode())) {
                    archive.setStatus("" + ApproveStatusEnum.DSH.getCode());
                } else if (userType != null && userType.equals(UserTypeEnum.ADMIN.getCode())) {
                    archive.setStatus("" + ApproveStatusEnum.YSH.getCode());
                }

                homeworkArchiveDAO.save(archive);

                // auto increment archives number.
                num++;
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } catch (NullPointerException e) {
        log.error("File name arguments missed.", e);

        throw new NullPointerException(e.getMessage());
    } finally {
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        if (bf != null) {
            try {
                bf.flush();
                bf.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    return false;
}

From source file:org.sakaiproject.imagegallery.integration.standalone.FileLibraryStandalone.java

/**
 * @see org.sakaiproject.imagegallery.integration.FileLibraryService#storeImageFile(org.springframework.web.multipart.MultipartFile)
 *//*from  w w  w . j  a va2 s  .  co  m*/
@Transactional
public ImageFile storeImageFile(final MultipartFile sourceImageFile) {
    final String filename = sourceImageFile.getOriginalFilename();
    final String fileId = contextService.getCurrentContextUid() + "/" + filename;
    final String contentType = sourceImageFile.getContentType();

    ImageFile imageFile = new ImageFile();
    imageFile.setContentType(contentType);
    imageFile.setFilename(filename);
    imageFile.setFileId(fileId);
    imageFile.setDataUrl(urlPrefix + fileId);

    jdbcTemplate.getJdbcOperations().execute(
            "insert into IMAGE_GALLERY_STANDALONE_FILES_T (FILE_ID, CONTENT_TYPE, CONTENT) VALUES (?, ?, ?)",
            new AbstractLobCreatingPreparedStatementCallback(this.lobHandler) {
                protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException {
                    ps.setString(1, fileId);
                    ps.setString(2, contentType);
                    try {
                        lobCreator.setBlobAsBinaryStream(ps, 3, sourceImageFile.getInputStream(),
                                (int) sourceImageFile.getSize());
                    } catch (IOException e) {
                        log.error("Error copying binary data from file " + filename, e);
                    }
                }
            });

    return imageFile;
}

From source file:com.chcit.scm.web.ent.action.BPartnerActionController.java

/**
 * /*from   w  w  w  .  j av a  2s . c  om*/
 */
public void importBPartner(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    InputStream in = null;
    try {
        int AD_Org_ID = Integer.valueOf(req.getParameter("AD_Org_ID"));
        int AD_Server_ID = getAD_Server_ID();

        String filekey = req.getParameter("filekey");

        int ediFormatId = DB.getSQLValue(
                "SELECT f.EDI_Format_ID FROM EDI_Format f join EDI_DOC d on (d.EDI_Doc_ID=f.EDI_Doc_ID) WHERE  f.IsActive='Y' AND d.Value='BPartner' AND f.AD_Server_ID=?",
                AD_Server_ID);

        if (ediFormatId == 0) {
            throw new Exception("?");
        }
        if (StringUtils.isEmpty(filekey))
            throw new Exception("");

        MultipartFile uploadfile = ((DefaultMultipartHttpServletRequest) req).getFile(filekey);
        String orginalFilename = uploadfile.getOriginalFilename();

        in = uploadfile.getInputStream();
        int row = ServiceManager.getService(EDIService.class).importBPartner(in, AD_Server_ID, AD_Org_ID,
                ediFormatId, true);
        StringBuffer log = new StringBuffer("?" + row + "");
        log.append("!");

        //System.out.println("count:=" + count);
        ProcessResult<JSON> pr = new ProcessResult<JSON>(true);
        pr.setMessage(log.toString());
        JSONObject jsonResult = new JSONObject();
        jsonResult.element("fileName", orginalFilename);
        pr.setData(jsonResult);
        sendJSON(resp, pr.toJSON());

    } catch (Exception e) {
        e.printStackTrace();
        throw new JsonResultException(e);
    } finally {
        if (in != null)
            in.close();
    }
}

From source file:com.osc.edu.chapter4.customers.CustomersController.java

@RequestMapping("/updateCustomers")
public String updateCustomers(@RequestParam(value = "imgFile", required = false) MultipartFile imgFile,
        @ModelAttribute @Valid CustomersDto customers, BindingResult results, SessionStatus status,
        HttpSession session) {//from  w  w w . j av a  2  s  . co m

    if (results.hasErrors()) {
        logger.debug("results : [{}]", results);
        return "customers/form";
    }

    try {
        if (imgFile != null && !imgFile.getOriginalFilename().equals("")) {
            String fileName = imgFile.getOriginalFilename();
            String destDir = session.getServletContext().getRealPath("/upload");

            File dirPath = new File(destDir);
            if (!dirPath.exists()) {
                boolean created = dirPath.mkdirs();
                if (!created) {
                    throw new Exception("Fail to create a directory for movie image. [" + destDir + "]");
                }
            }

            IOUtils.copy(imgFile.getInputStream(), new FileOutputStream(new File(destDir, fileName)));

            logger.debug("Upload file({}) saved to [{}].", fileName, destDir);
        }
        customersService.updateCustomers(customers);
        status.setComplete();
    } catch (Exception e) {
        logger.debug("Exception has occurred. ", e);
    }

    return "redirect:/customers/getCustomersList.do";
}