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.album.controller.AlbumController.java

/**
 * /*from   w w w.  j a va  2 s. c  o  m*/
 *
 * @param album 
 * @param bindingResult 
 * @return ajax?
 * @throws Exception 
 */
@RequestMapping(value = "/edit", method = RequestMethod.POST)
public void editAlbum(@Valid Album album, HttpServletRequest request, BindingResult bindingResult,
        HttpServletResponse response) throws Exception {
    //      AJAX?
    AjaxResponse ajaxResponse = new AjaxResponse();
    //      ??
    if (bindingResult.hasErrors()) {
        ajaxResponse.bindingResultHandler(bindingResult);
        //           ?
        LogUtils.updateOperationLog(request, OperationType.UPDATE,
                "id" + album.getAlbum_id() + "??"
                        + album.getAlbum_name() + "?"
                        + AjaxResponse.getBindingResultMessage(bindingResult) + "");
        response.setContentType("text/html;charset=utf-8");
        JSONObject obj = JSONObject.fromObject(ajaxResponse);
        response.getWriter().write(obj.toString());
        return;
    }
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("picture");
    String fileName = multipartFile.getOriginalFilename();
    //?
    String path = null;
    if (null != multipartFile && StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) {
        JSONObject jobj = FileUploadClient.upFile(request, fileName, multipartFile.getInputStream());
        if (jobj.getString("responseMessage").equals("OK")) {
            path = jobj.getString("fpath");
        }
    }
    /*
    if (fileName.trim().length() > 0) {
    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();
        }
    }
    path = path.replaceAll("\\\\", "/");
    album.setAlbum_coverpath(path);
    }
    */
    if (null != path) {
        album.setAlbum_coverpath(path);
    }
    //      ????
    Date nowDate = new Date();
    //      ?
    album.setAlbum_updatedate(nowDate);
    album.setAlbum_flag("1");
    //      
    dao.updateAlbum(album);
    //      ????
    ajaxResponse.setSuccess(true);
    ajaxResponse.setSuccessMessage("??");
    //?
    Map map = new HashMap();
    map.put("URL", basePath + "album");
    ajaxResponse.setExtParam(map);
    //      ?
    LogUtils.updateOperationLog(request, OperationType.UPDATE,
            "id" + album.getAlbum_id() + "??" + album.getAlbum_name());
    response.setContentType("text/html;charset=utf-8");
    JSONObject obj = JSONObject.fromObject(ajaxResponse);
    response.getWriter().write(obj.toString());
}

From source file:app.service.ResourceService.java

public int upload(MultipartFile file, int resourceType, StringResource resource) {
    if (file.isEmpty()) {
        return ResultCode.FILE_EMPTY;
    }/*ww w  .ja  v  a2s  .co  m*/

    String path;
    if (resourceType == RESOURCE_TYPE_AVATAR) {
        path = RESOURCE_AVATAR_PATH;
    } else if (resourceType == RESOURCE_TYPE_COMMON) {
        path = RESOURCE_COMMON_PATH;
    } else {
        return ResultCode.UNKNOWN_RESOURCE;
    }

    resolvePath(path);
    String filename = resolveFilename(file.getOriginalFilename());
    try {
        OutputStream out = new FileOutputStream(new File(path + "/" + filename));
        BufferedOutputStream stream = new BufferedOutputStream(out);
        FileCopyUtils.copy(file.getInputStream(), stream);
        stream.close();
        resource.filename = filename;
    } catch (Exception e) {
        logger.warn("upload file failure", e);
        return ResultCode.UPLOAD_FILE_FAILED;
    }
    return BaseResponse.COMMON_SUCCESS;
}

From source file:com.sliu.framework.app.process.controller.ProcessXNController.java

/**
 * ?,??????API/*from  w ww  .j av  a  2  s  . c  om*/
 */
@RequestMapping(value = "/deployProcess", method = RequestMethod.POST)
@ResponseBody
public String deployProcess(@RequestParam("attachMentFile") MultipartFile multipartFile)
        throws FileNotFoundException {

    if (multipartFile != null && multipartFile.getSize() != 0) {
        //,???
        FileCommonOperate fileCommonOperate = new FileCommonOperate();
        try {
            String fileName = fileCommonOperate.uploadFile(multipartFile.getInputStream(), deployFilePath,
                    multipartFile.getOriginalFilename());
            InputStream fileInputStream = multipartFile.getInputStream();
            String extension = FilenameUtils.getExtension(fileName);
            if (extension.equals("zip") || extension.equals("bar")) {
                ZipInputStream zip = new ZipInputStream(fileInputStream);
                repositoryService.createDeployment().addZipInputStream(zip).deploy();
            } else {
                repositoryService.createDeployment().addInputStream(fileName, fileInputStream).deploy();
            }
        } catch (IOException e) {
            e.printStackTrace();

        }
    }
    return "{success:true}";
}

From source file:com.dlshouwen.wzgl.album.controller.AlbumController.java

/**
 * //from   w w w  .  j  av  a  2 s  . c om
 *
 * @param album 
 * @param bindingResult 
 * @param request 
 * @return ajax?
 * @throws Exception 
 */
@RequestMapping(value = "/add", method = RequestMethod.POST)
public void addAlbum(@Valid Album album, BindingResult bindingResult, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    AjaxResponse ajaxResponse = new AjaxResponse();

    if (bindingResult.hasErrors()) {
        ajaxResponse.bindingResultHandler(bindingResult);
        LogUtils.updateOperationLog(request, OperationType.INSERT,
                "??" + album.getAlbum_name() + "?"
                        + AjaxResponse.getBindingResultMessage(bindingResult) + "");
        response.setContentType("text/html;charset=utf-8");
        JSONObject obj = JSONObject.fromObject(ajaxResponse);
        response.getWriter().write(obj.toString());
        return;
    }
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("picture");
    String fileName = multipartFile.getOriginalFilename();
    //?
    String path = null;
    if (null != multipartFile && StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) {
        JSONObject jobj = FileUploadClient.upFile(request, fileName, multipartFile.getInputStream());
        if (jobj.getString("responseMessage").equals("OK")) {
            path = jobj.getString("fpath");
        }
    }
    /*
    if (fileName.trim().length() > 0) {
    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();
        }
    }
    path = path.replaceAll("\\\\", "/");
    album.setAlbum_coverpath(path);
    }
    */
    if (null != path) {
        album.setAlbum_coverpath(path);
    }
    //      ????
    SessionUser sessionUser = (SessionUser) request.getSession().getAttribute(CONFIG.SESSION_USER);
    String userName = sessionUser.getUser_name();
    String userId = sessionUser.getUser_id();
    Date nowDate = new Date();
    //      ?????
    album.setAlbum_id(new GUID().toString());
    album.setAlbum_createuser(userName);
    album.setAlbum_createuserbyid(userId);
    album.setAlbum_createdate(nowDate);

    //      
    dao.insertAlbum(album);
    //      ????
    ajaxResponse.setSuccess(true);
    ajaxResponse.setSuccessMessage("??");
    //?
    Map map = new HashMap();
    map.put("URL", basePath + "album");
    ajaxResponse.setExtParam(map);

    //      ?
    LogUtils.updateOperationLog(request, OperationType.INSERT,
            "id" + album.getAlbum_id() + "??" + album.getAlbum_name());
    response.setContentType("text/html;charset=utf-8");
    JSONObject obj = JSONObject.fromObject(ajaxResponse);
    response.getWriter().write(obj.toString());
    return;
}

From source file:egovframework.oe1.cms.arc.web.EgovOe1ScrinController.java

/**
 * ??   ?./*from   w w w  .  j a va  2  s  .c o m*/
 * @param ?  scrinVO, request, model
 * @return forward:/cms/arc/selectScrin.do";
 * @exception Exception
 */
@RequestMapping(value = "/cms/arc/excelScrinRegist.do")
public String insertExcelScrin(@ModelAttribute("scrinVO") EgovOe1ScrinVO scrinVO,
        final HttpServletRequest request, Map commandMap, Model model) throws Exception {

    // Spring Security
    Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
    if (!isAuthenticated) {
        return "/cms/com/EgovLoginUsr"; // ? ??
    }

    // 
    EgovOe1LoginVO user = (EgovOe1LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
    scrinVO.setFrstRegisterId(user.getMberId());

    String sCmd = commandMap.get("cmd") == null ? "" : (String) commandMap.get("cmd");
    if (sCmd.equals("")) {
        return "/cms/arc/EgovExcelScrinRegist";
    }
    final MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
    final Map<String, MultipartFile> files = multiRequest.getFileMap();

    Iterator<Entry<String, MultipartFile>> itr = files.entrySet().iterator();
    MultipartFile file;

    while (itr.hasNext()) {
        Entry<String, MultipartFile> entry = itr.next();

        file = entry.getValue();
        if (!"".equals(file.getOriginalFilename())) {
            // ? ??    .
            egovOe1ScrinService.deleteExcelScrin();

            InputStream is = null;
            try {
                is = file.getInputStream();
                excelService.uploadExcel("egovOe1ScrinDAO.inserExceltScrin", is, 4);
            } catch (Exception e) {
                throw e;
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (Exception e) {
                    // log none
                    log.info(e.getMessage());
                }
            }
        }
    }

    return "forward:/cms/arc/selectScrin.do";
}

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

private boolean updateChecksumFile(MultipartHttpServletRequest request, JobIdentifier jobIdentifier,
        String filePath) throws IOException, IllegalArtifactLocationException {
    MultipartFile checksumMultipartFile = getChecksumFile(request);
    if (checksumMultipartFile != null) {
        String checksumFilePath = String.format("%s/%s/%s", artifactsService.findArtifactRoot(jobIdentifier),
                ArtifactLogUtil.CRUISE_OUTPUT_FOLDER, ArtifactLogUtil.MD5_CHECKSUM_FILENAME);
        File checksumFile = artifactsService.getArtifactLocation(checksumFilePath);
        synchronized (checksumFilePath.intern()) {
            return artifactsService.saveOrAppendFile(checksumFile, checksumMultipartFile.getInputStream());
        }/*from ww  w .ja  va  2s.com*/
    } else {
        LOGGER.warn("[Artifacts Upload] Checksum file not uploaded for artifact at path '{}'", filePath);
    }
    return true;
}

From source file:com.dlshouwen.wzgl.video.controller.VideoController.java

/**
 * // w  w  w. j  ava  2 s.  c  o  m
 *
 * @param request
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public AjaxResponse uploadVideo(HttpServletRequest request, HttpServletResponse response) throws Exception {
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("file");
    String fileName = multipartFile.getOriginalFilename();

    //?
    String path = null;
    String videoCoverPath = null;
    String videoTime = null;
    if (null != multipartFile && StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) {
        JSONObject jobj = FileUploadClient.upFile(request, fileName, multipartFile.getInputStream());
        if (jobj.getString("responseMessage").equals("OK")) {
            path = jobj.getString("fpath");
            videoCoverPath = jobj.getString("videoCoverPath");
            videoTime = jobj.getString("videoTime");
        }
    }
    /*
    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_VIDEO_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();
    }
    }
    */

    AjaxResponse ajaxResponse = new AjaxResponse();
    if (StringUtils.isNotEmpty(path)) {
        WebUtil.addCookie(request, response, "videoPath", path, -1);
        WebUtil.addCookie(request, response, "videoCoverPath", videoCoverPath, -1);
        WebUtil.addCookie(request, response, "videoTime", videoTime, -1);
        //      ?
        ajaxResponse.setSuccess(true);
        ajaxResponse.setSuccessMessage("??");
    } else {
        //      ?
        ajaxResponse.setError(true);
        ajaxResponse.setErrorMessage("?");
    }
    //      ?
    LogUtils.updateOperationLog(request, OperationType.UPDATE,
            "??" + fileName);
    return ajaxResponse;
}

From source file:com.dlshouwen.tdjs.picture.controller.TdjsPictureController.java

/**
 * //  w w w. j av  a 2s.c  o  m
 *
 * @param picture 
 * @param bindingResult ?
 * @param request 
 * @return ajax?
 */
@RequestMapping(value = "/{albumId}/ajaxMultipartAdd", method = RequestMethod.POST)
@ResponseBody
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");
    String path = "";
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("file");
    String sname = multipartFile.getOriginalFilename();
    if (multipartFile != null && StringUtils.isNotEmpty(sname)) {
        JSONObject jobj = FileUploadClient.upFile(request, sname, multipartFile.getInputStream());
        if (jobj != null && jobj.getString("responseMessage").equals("OK")) {
            path = jobj.getString("fpath");
        }
    }

    //??
    picture.setPicture_name(sname);

    //      ????
    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_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");

    //
    Album album = albumDao.getAlbumById(albumId);
    String team_id = album.getTeam_id();
    String team_name = album.getTeam_name();
    picture.setTeam_id(team_id);
    picture.setTeam_name(team_name);

    picture.setUpdate_time(new Date());

    //      
    dao.insertPicture(picture);

    //??,????
    if (StringUtils.isNotEmpty(flag) && flag.equals("article")) {
        if (StringUtils.isEmpty(album.getAlbum_coverpath())) {
            albumDao.setAlbCover(albumId, picture.getPath());
        }
    }

    //      ????
    ajaxResponse.setSuccess(true);
    ajaxResponse.setSuccessMessage("??");

    //      ?
    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:com.example.ekanban.service.ProductService.java

@Transactional
public void addProductsBatch(MultipartFile file) {
    logger.debug("addProductsBatch");
    List<ProductCsv> list = null;
    //convert to csv string
    String output = null;/*  w ww  .  j  av a 2s .c om*/
    try {
        if (file.getOriginalFilename().contains("xlsx")) {
            output = CsvUtils.fromXlsx(file.getInputStream());
        } else if (file.getOriginalFilename().contains("xls")) {
            output = CsvUtils.fromXls(file.getInputStream());
        }
        //logger.debug(output);
    } catch (IOException e) {
        e.printStackTrace();
    }

    //Read as Bean from csv String
    CSVReader reader = new CSVReader(new StringReader(output), ';');
    HeaderColumnNameMappingStrategy<ProductCsv> strategy = new HeaderColumnNameMappingStrategy<>();
    strategy.setType(ProductCsv.class);
    CsvToBean<ProductCsv> csvToBean = new CsvToBean<>();
    list = csvToBean.parse(strategy, reader);
    //Validate Product Data
    validate(list);

    //convert from DTO to ENTITY
    List<Product> products = map(list);
    productRepository.save(products);
}