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

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

Introduction

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

Prototype

default void transferTo(Path dest) throws IOException, IllegalStateException 

Source Link

Document

Transfer the received file to the given destination file.

Usage

From source file:com.poscoict.license.service.ManagementService.java

@SuppressWarnings("unchecked")
public String plusProduct(ContractProductInfo info, String userNo, HttpSession session) throws UserException {
    logger.info("plusProduct: userNo= " + userNo);
    TransactionStatus status = this.transactionManager.getTransaction(new DefaultTransactionDefinition());
    try {/*  w  w w  .  j  av  a  2  s  . co  m*/
        String licenseUpPath = Consts.LICENSE_FILE_HOME;
        if (info != null) {
            ArrayList<MultipartFile> upFileList = (ArrayList<MultipartFile>) info.getFile();
            ArrayList<String> proIdList = (ArrayList<String>) info.getPRODUCT_FILE_ID();
            ArrayList<String> licenseKeyList = (ArrayList<String>) info.getLICENSE_KEY();
            ArrayList<String> quantityList = (ArrayList<String>) info.getLICENSE_QUANTITY();
            ArrayList<String> fileCheckList = (ArrayList<String>) info.getCHECKBOX();
            for (int i = 0; i < proIdList.size(); i++) {
                String path = "";
                String licenseName = ""; // ???

                String objectId = proIdList.get(i);
                String licenseKey = licenseKeyList.get(i);
                String quantity = quantityList.get(i);
                String fileCheck = fileCheckList.get(i);

                if (fileCheck.equals("false")) {
                    try {
                        MultipartFile upFile = upFileList.get(i);
                        licenseName = upFile.getOriginalFilename(); // ???

                        File upfile = new File(licenseUpPath + userNo + File.separator + licenseName);
                        if (upfile.isFile())
                            throw new UserException(
                                    "???? . ??  .");

                        if (!upfile.exists())
                            upfile.mkdirs();

                        upFile.transferTo(upfile);
                        path = upfile.getAbsolutePath();
                        logger.info("plusProduct: upFileName= " + licenseName + " path= " + path);
                    } catch (IOException e) {
                        logger.error("plusProduct(File Upload Error): ", e);
                    }
                }

                // ?? 
                managementDao.addLicenseInfo(userNo, licenseKey, objectId,
                        (String) session.getAttribute("USER_NO"), path, licenseName, quantity);
            }
        }
        this.transactionManager.commit(status);
    } catch (DuplicateKeyException e) {
        this.transactionManager.rollback(status);
        logger.error("plusProduct: ", e);
        throw new DuplicateKeyException(
                " ?. ?? ? .");
    } catch (RuntimeException e) {
        this.transactionManager.rollback(status);
        logger.error("plusProduct: ", e);
    }

    return userNo;
}

From source file:com.topsec.tsm.sim.sysconfig.web.SystemConfigController.java

@RequestMapping(value = "modifyCompanyInfo")
@ResponseBody//from  w  w  w  . j  av  a2 s .  c o  m
public Object modifyCompanyInfo(@RequestParam(value = "companyLogoFile") MultipartFile companyLogoFile,
        HttpServletRequest request) throws Exception {
    Result result = new Result();
    String companyName = StringUtil.recode(request.getParameter("companyName"));
    String productName = StringUtil.recode(request.getParameter("productName"));
    String companyLogo = companyLogoFile.getOriginalFilename();
    String path = request.getSession().getServletContext().getRealPath("/");
    String logoPath = "";
    if (StringUtil.isNotBlank(companyLogo)) {
        if (companyLogoFile.getSize() > 1024 * 1024) {
            return result.buildError("?1M?logo");
        }
        logoPath = "/img/skin/top/user_logo." + FilenameUtils.getExtension(companyLogo);
        String filePath = path + logoPath;
        companyLogoFile.transferTo(new File(filePath));
        BufferedImage src = javax.imageio.ImageIO.read(new File(filePath));
        int width = src.getWidth();
        int height = src.getHeight();
        if (width > 500 || width < 300 || height > 51 || height < 40) {
            return result.buildError(
                    "300px~500px?40px~51px?logo(425px*51px)");
        }
    }
    companyLogo = StringUtil.isBlank(companyLogo) ? CommonUtils.getCompanyLogo() : logoPath;
    companyName = StringUtil.ifBlank(companyName, CommonUtils.getCompanyName());
    productName = StringUtil.ifBlank(productName, CommonUtils.getProductName());
    CommonUtils.setCompanyInfo(companyLogo, companyName, productName);
    return result.build(true, "?");
}

From source file:org.shareok.data.sagedata.SageSourceDataHandlerImpl.java

/**
 * //from   w  w w. ja  va2  s  .  co  m
 * @param file : the uploaded file
 * @return : the path to the saved uploaded file
 */
@Override
public String saveUploadedData(MultipartFile file) {
    String uploadedFilePath = null;
    try {
        String oldFileName = file.getOriginalFilename();
        String extension = DocumentProcessorUtil.getFileExtension(oldFileName);
        oldFileName = DocumentProcessorUtil.getFileNameWithoutExtension(oldFileName);
        //In the future the new file name will also has the user name
        String time = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
        String newFileName = oldFileName + "--" + time + "." + extension;
        String uploadPath = ShareokdataManager.getSageUploadPath();
        if (null != uploadPath) {
            File uploadFolder = new File(uploadPath);
            if (!uploadFolder.exists()) {
                uploadFolder.mkdir();
            }
            File uploadTimeFolder = new File(uploadPath + File.separator + time);
            if (!uploadTimeFolder.exists()) {
                uploadTimeFolder.mkdir();
            }
        }
        uploadedFilePath = uploadPath + File.separator + time + File.separator + newFileName;
        File uploadedFile = new File(uploadedFilePath);
        file.transferTo(uploadedFile);
    } catch (Exception ex) {
        Logger.getLogger(SageSourceDataHandlerImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
    return uploadedFilePath;
}

From source file:com.poscoict.license.service.ManagementService.java

@SuppressWarnings("unchecked")
public void newContract(ContractPersonInfo per, ContractProductInfo pro, String[] etcFile, HttpSession session)
        throws UserException {
    logger.info("newContract");
    TransactionStatus status = this.transactionManager.getTransaction(new DefaultTransactionDefinition());
    try {/*  w ww. ja  va  2s .  c o m*/
        System.out.println("company: " + per.getORDER_COMPANY_CODE());
        String licenseUpPath = Consts.LICENSE_FILE_HOME;

        String userNo = per.getUSER_NO();

        if (pro != null) {
            ArrayList<MultipartFile> upFileList = (ArrayList<MultipartFile>) pro.getFile();
            ArrayList<String> productList = (ArrayList<String>) pro.getPRODUCT_FILE_ID();
            ArrayList<String> licenseKeyList = (ArrayList<String>) pro.getLICENSE_KEY();
            ArrayList<String> quantityList = (ArrayList<String>) pro.getLICENSE_QUANTITY();
            ArrayList<String> fileCheckList = (ArrayList<String>) pro.getCHECKBOX();

            for (int i = 0; i < productList.size(); i++) {
                String licensePath = "";

                String licenseName = "";
                String objectId = productList.get(i);
                String licenseKey = licenseKeyList.get(i);
                String quantity = quantityList.get(i);
                String fileCheck = fileCheckList.get(i);
                if (fileCheck.equals("false")) {
                    MultipartFile upFile = upFileList.get(i);
                    licenseName = upFile.getOriginalFilename(); // ???
                    logger.info("newContract: fileName= " + licenseName);
                    try {
                        File upfile = new File(licenseUpPath + userNo + File.separator + licenseName);

                        if (upfile.isFile())
                            throw new UserException(
                                    "???? . ??  .");

                        if (!upfile.exists())
                            upfile.mkdirs();

                        upFile.transferTo(upfile);
                        licensePath = upfile.getAbsolutePath();
                        logger.info("newContract: licensePath= " + licensePath);
                    } catch (IOException e) {
                        logger.error("newContract(File Upload Error): ", e);
                    }
                    // ?? 
                }
                managementDao.addLicenseInfo(userNo, licenseKey, objectId,
                        (String) session.getAttribute("USER_NO"), licensePath, licenseName, quantity);
            }
        }
        if (etcFile != null) {
            for (int i = 0; i < etcFile.length; i++) {
                String etcId = etcFile[i];
                managementDao.addUserEtcFileInfo(userNo, etcId, (String) session.getAttribute("USER_NO"));
            }
        }

        //  
        managementDao.addUser(per, (String) session.getAttribute("USER_NO"), passwordEncoder(userNo),
                Consts.USERLV_PUBLIC);
        //   
        Map<String, Object> map = getClientPermission();
        String codes = (String) map.get("codes");
        String codeTypes = (String) map.get("codeTypes");
        int size = (Integer) map.get("size");

        logger.info("codes : " + codes);
        logger.info("codeTypes : " + codeTypes);
        logger.info("size : " + size);
        logger.info("userNo : " + userNo);

        managementDao.insert_user_permission(codes, codeTypes, userNo, size);

        // ??  ??
        if (!per.getPRODUCT_SETUP_DATE().isEmpty()) {
            managementDao.updateProductSetupDate(userNo, per.getPRODUCT_SETUP_DATE());
        }
        this.transactionManager.commit(status);
    } catch (DuplicateKeyException e) {
        this.transactionManager.rollback(status);
        logger.error("plusProduct: ", e);
        throw new DuplicateKeyException(
                " ?. ?? ? .");
    } catch (RuntimeException e) {
        this.transactionManager.rollback(status);
        logger.error("plusProduct: ", e);
    }

    //        return "redirect:/management";
}

From source file:de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.RemoteApiController.java

/**
 * Create a new project./*from   w  w w  .  ja v a  2 s .  c  om*/
 *
 * To test, use the Linux "curl" command.
 *
 * curl -v -F 'file=@test.zip' -F 'name=Test' -F 'filetype=tcf'
 * 'http://USERNAME:PASSWORD@localhost:8080/de.tudarmstadt.ukp.clarin.webanno.webapp/api/project
 * '
 *
 * @param aName
 *            the name of the project to create.
 * @param aFileType
 *            the type of the files contained in the ZIP. The possible file types are configured
 *            in the formats.properties configuration file of WebAnno.
 * @param aFile
 *            a ZIP file containing the project data.
 * @throws Exception if there was en error.
 */
@RequestMapping(value = "/project", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public @ResponseStatus(HttpStatus.NO_CONTENT) void createProject(@RequestParam("file") MultipartFile aFile,
        @RequestParam("name") String aName, @RequestParam("filetype") String aFileType) throws Exception {
    LOG.info("Creating project [" + aName + "]");

    if (!ZipUtils.isZipStream(aFile.getInputStream())) {
        throw new InvalidFileNameException("", "is an invalid Zip file");
    }

    // Get current user
    String username = SecurityContextHolder.getContext().getAuthentication().getName();
    User user = userRepository.get(username);
    Project project = null;

    // Configure project
    if (!projectRepository.existsProject(aName)) {
        project = new Project();
        project.setName(aName);

        // Create the project and initialize tags
        projectRepository.createProject(project, user);
        annotationService.initializeTypesForProject(project, user, new String[] {}, new String[] {},
                new String[] {}, new String[] {}, new String[] {}, new String[] {}, new String[] {},
                new String[] {});
        // Create permission for this user
        ProjectPermission permission = new ProjectPermission();
        permission.setLevel(PermissionLevel.ADMIN);
        permission.setProject(project);
        permission.setUser(username);
        projectRepository.createProjectPermission(permission);

        permission = new ProjectPermission();
        permission.setLevel(PermissionLevel.USER);
        permission.setProject(project);
        permission.setUser(username);
        projectRepository.createProjectPermission(permission);
    }
    // Existing project
    else {
        throw new IOException("The project with name [" + aName + "] exists");
    }

    // Iterate through all the files in the ZIP

    // If the current filename does not start with "." and is in the root folder of the ZIP,
    // import it as a source document
    File zimpFile = File.createTempFile(aFile.getOriginalFilename(), ".zip");
    aFile.transferTo(zimpFile);
    ZipFile zip = new ZipFile(zimpFile);

    for (Enumeration<?> zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) {
        //
        // Get ZipEntry which is a file or a directory
        //
        ZipEntry entry = (ZipEntry) zipEnumerate.nextElement();

        // If it is the zip name, ignore it
        if ((FilenameUtils.removeExtension(aFile.getOriginalFilename()) + "/").equals(entry.toString())) {
            continue;
        }
        // IF the current filename is META-INF/webanno/source-meta-data.properties store it
        // as
        // project meta data
        else if (entry.toString().replace("/", "")
                .equals((META_INF + "webanno/source-meta-data.properties").replace("/", ""))) {
            InputStream zipStream = zip.getInputStream(entry);
            projectRepository.savePropertiesFile(project, zipStream, entry.toString());

        }
        // File not in the Zip's root folder OR not
        // META-INF/webanno/source-meta-data.properties
        else if (StringUtils.countMatches(entry.toString(), "/") > 1) {
            continue;
        }
        // If the current filename does not start with "." and is in the root folder of the
        // ZIP, import it as a source document
        else if (!FilenameUtils.getExtension(entry.toString()).equals("")
                && !FilenameUtils.getName(entry.toString()).equals(".")) {

            uploadSourceDocument(zip, entry, project, user, aFileType);
        }

    }

    LOG.info("Successfully created project [" + aName + "] for user [" + username + "]");

}

From source file:com.node.action.UserAction.java

private String uploadImg(HttpServletRequest request, MultipartFile file)
        throws FileNotFoundException, IOException {
    if (!file.isEmpty()) {
        PicPath imgPath = iCompanyService.getPathById(SystemConstants.PIC_IMG);
        String source = imgPath.getVcAddpath();// ?
        SimpleDateFormat format = new SimpleDateFormat("yyMMdd");
        source = source + "/" + format.format(new Date());
        if (!source.endsWith("/")) {
            source += "/";
        }//ww  w . ja v  a  2s .  com
        if (StringUtils.isBlank(source)) {
            System.out.println("source??");
            return null;
        }
        String getImagePath = source;

        // ???
        String uploadName = file.getContentType();
        System.out.println(" ------------" + uploadName);

        String lastuploadName = uploadName.substring(uploadName.indexOf("/") + 1, uploadName.length());
        System.out.println("??? ------------" + lastuploadName);

        // ??
        String fileNewName = generateFileName(file.getOriginalFilename());
        System.out.println("// ?? ------------" + fileNewName);

        // ?
        String imagePath = source + "/" + fileNewName;
        System.out.println("        //?   " + imagePath);
        File image = new File(getImagePath);
        if (!image.exists()) {
            image.mkdir();
        }
        // file.transferTo(pathFile);
        BufferedImage srcBufferImage = ImageIO.read(file.getInputStream());
        BufferedImage scaledImage;
        ScaleImage scaleImage = new ScaleImage();
        int yw = srcBufferImage.getWidth();
        int yh = srcBufferImage.getHeight();
        int w = SystemConstants.IMG_LICENCE_WITH, h = SystemConstants.IMG_LICENCE_HEIGHT;
        if (w > yw && h > yh) {
            File image2 = new File(getImagePath, fileNewName);
            file.transferTo(image2);
        } else {
            scaledImage = scaleImage.imageZoomOut(srcBufferImage, w, h);
            FileOutputStream out = new FileOutputStream(getImagePath + "/" + fileNewName);
            ImageIO.write(scaledImage, "jpeg", out);
            out.close();
        }
        return format.format(new Date()) + "/" + fileNewName;// ????
    } else {
        return null;
    }
}

From source file:com.poscoict.license.service.ManagementService.java

public void upload(String folder, String packageVersion, MultipartFile file, String comment, String mode,
        HttpSession session) throws Exception {
    TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
    try {/* ww  w  . j  a va  2s . c o  m*/
        String folderPath = getFolderPath(folder);
        String objectId = "";
        if (mode.equals("package")) {
            if (packageVersion != null && packageVersion != "") {
                folderPath += packageVersion + File.separator;
                objectId = "pk_" + attachFileDateFormat()
                        + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 12);
            }
        } else {
            folderPath += packageVersion + File.separator + "patch" + File.separator;
            objectId = "pt_" + attachFileDateFormat()
                    + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 12);
            ;
        }

        MultipartFile upFile = file;
        String fileName = null;
        if (upFile != null) {
            fileName = upFile.getOriginalFilename();
            System.out.println("up: fileName: " + fileName + " " + folderPath);
            if (mode.equals("package")) {
                managementDao.addFileInfo(objectId, folder, folder.equals("etc") ? fileName : packageVersion,
                        fileName, comment.replaceAll("\n", "<br>"), folderPath + fileName,
                        (String) session.getAttribute("USER_NO"));
            } else {
                String pObjectId = managementDao.getProductKey(folder, packageVersion);
                managementDao.addPatchFileInfo(objectId, pObjectId, folder, packageVersion, fileName,
                        comment.replaceAll("\n", "<br>"), folderPath + fileName,
                        (String) session.getAttribute("USER_NO"));
            }
            try {
                File ufile = new File(folderPath + fileName);

                if (ufile.isFile()) {
                    logger.error("upload- Duplicate FileName: " + folderPath + fileName);
                    throw new UserException(
                            "???? . ??  .");
                }

                if (!ufile.exists()) {
                    ufile.mkdirs();
                }
                upFile.transferTo(ufile);
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("packageUpload/patchUpload(File Upload Error): ", e);
                throw new IOException();
            }
        }
        this.transactionManager.commit(status);
    } catch (DuplicateKeyException e) {
        this.transactionManager.rollback(status);
        logger.error("packageUpload/patchUpload(File Upload Error): ", e);
        throw new DuplicateKeyException(
                " ?. ?? ? .");
    } catch (Exception e) {
        this.transactionManager.rollback(status);
        logger.error("packageUpload/patchUpload(File Upload Error): ", e);
        throw new Exception(e);
    }
}

From source file:org.cloudifysource.rest.controllers.ServiceController.java

private File copyMultipartFileToLocalFile(final MultipartFile srcFile) throws IOException {
    if (srcFile == null) {
        return null;
    }// w  w w  . jav  a  2 s .c  o m
    final File tempFile = new File(restTemporaryFolder, srcFile.getOriginalFilename());
    srcFile.transferTo(tempFile);
    tempFile.deleteOnExit();
    return tempFile;
}

From source file:egovframework.example.sample.web.EgovSampleController.java

@RequestMapping("/fileUploadX.do")
public void fileUploadX(HttpServletRequest request, HttpServletResponse response, SessionStatus status)
        throws Exception {
    //System.out.println(" ? uuid--"+request.getParameter("uuid"));
    String chkType = request.getHeader("Content-Type");

    if (chkType == null) {
        return;//from  w  ww. j a v  a  2  s .  c om
    }

    request.setCharacterEncoding("utf-8");
    String contextRealPath = request.getSession().getServletContext().getRealPath("/");
    String PATH = request.getParameter("PATH");
    String savePath = contextRealPath + PATH;
    //   System.out.println("savePath------@@-----"+savePath);
    //   int maxSize = 500 * 1024 * 1024; //   ? ? 500MB() 

    PlatformData resData = new PlatformData();
    VariableList resVarList = resData.getVariableList();
    String sMsg = " A ";
    try {
        MultipartHttpServletRequest msReq = (MultipartHttpServletRequest) request;
        Iterator<String> filesd = msReq.getFileNames();

        String dir = request.getRealPath("images/egovframework/board_img");
        while (filesd.hasNext()) {
            sMsg += "D ";
            //String name = (String)files.nextElement();
            String name = filesd.next();
            //   System.out.println("? ^^-----"+name);
            MultipartFile mfile = msReq.getFile(name);

            //?
            String genId = UUID.randomUUID().toString();

            //?
            String originalFileName = mfile.getOriginalFilename();
            //?
            String saveFileName = genId;

            //         System.out.println("???="+ originalFileName);
            System.out.println("??=" + saveFileName);

            String savePathh = dir + "/" + saveFileName;

            mfile.transferTo(new File(savePathh));

            System.out.println(name + "??");
            System.out.println("? ?-" + genId);
            //??
            SampleVO vo = new SampleVO();
            vo.setiOriName(originalFileName);
            vo.setiFileName(saveFileName);
            vo.setiSize((int) mfile.getSize());
            vo.setiUrl(savePathh);
            vo.setiUuid(request.getParameter("uuid"));
            sampleService.uploadImg(vo);
            status.setComplete();

        }

        resVarList.add("ErrorCode", 200);
        resVarList.add("ErrorMsg", "SUCC");
    } catch (Exception e) {
        resVarList.add("ErrorCode", 500);
        resVarList.add("ErrorMsg", sMsg + " " + e);

    }

    HttpPlatformResponse res = new HttpPlatformResponse(response);
    res.setData(resData);
    res.sendData();

}