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

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

Introduction

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

Prototype

long getSize();

Source Link

Document

Return the size of the file in bytes.

Usage

From source file:com.glaf.core.web.springmvc.FileUploadController.java

@ResponseBody
@RequestMapping("/upload")
public void upload(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/plain;charset=UTF-8");
    LoginContext loginContext = RequestUtils.getLoginContext(request);
    String serviceKey = request.getParameter("serviceKey");
    String responseType = request.getParameter("responseType");
    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug("paramMap:" + paramMap);
    MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
    String type = req.getParameter("type");
    if (StringUtils.isEmpty(type)) {
        type = "0";
    }/*w  w w.  ja  v  a2  s.  c o m*/
    int maxUploadSize = conf.getInt(serviceKey + ".maxUploadSize", 0);
    if (maxUploadSize == 0) {
        maxUploadSize = conf.getInt("upload.maxUploadSize", 50);// 50MB
    }
    maxUploadSize = maxUploadSize * FileUtils.MB_SIZE;

    /**
     * ?maxDiskSize,5MB
     */
    int maxDiskSize = conf.getInt(serviceKey + ".maxDiskSize", 0);
    if (maxDiskSize == 0) {
        maxDiskSize = conf.getInt("upload.maxDiskSize", 1024 * 1024 * 2);// 2MB
    }

    logger.debug("maxUploadSize:" + maxUploadSize);
    String uploadDir = Constants.UPLOAD_PATH;
    InputStream inputStream = null;
    try {
        PrintWriter out = response.getWriter();
        Map<String, MultipartFile> fileMap = req.getFileMap();
        Set<Entry<String, MultipartFile>> entrySet = fileMap.entrySet();
        for (Entry<String, MultipartFile> entry : entrySet) {
            MultipartFile mFile = entry.getValue();
            logger.debug("fize size:" + mFile.getSize());
            if (mFile.getOriginalFilename() != null && mFile.getSize() > 0 && mFile.getSize() < maxUploadSize) {
                String filename = mFile.getOriginalFilename();
                logger.debug("upload file:" + filename);
                logger.debug("fize size:" + mFile.getSize());
                String fileId = UUID32.getUUID();

                // ????
                String autoCreatedDateDirByParttern = "yyyy/MM/dd";
                String autoCreatedDateDir = DateFormatUtils.format(new java.util.Date(),
                        autoCreatedDateDirByParttern);
                String rootDir = SystemProperties.getConfigRootPath();
                if (!rootDir.endsWith(String.valueOf(File.separatorChar))) {
                    rootDir = rootDir + File.separatorChar;
                }
                File savePath = new File(rootDir + uploadDir + autoCreatedDateDir);
                if (!savePath.exists()) {
                    savePath.mkdirs();
                }

                String fileName = savePath + "/" + fileId;

                BlobItem dataFile = new BlobItemEntity();
                dataFile.setLastModified(System.currentTimeMillis());
                dataFile.setCreateBy(loginContext.getActorId());
                dataFile.setFileId(fileId);
                dataFile.setPath(uploadDir + autoCreatedDateDir + "/" + fileId);
                dataFile.setFilename(mFile.getOriginalFilename());
                dataFile.setName(mFile.getOriginalFilename());
                dataFile.setContentType(mFile.getContentType());
                dataFile.setType(type);
                dataFile.setStatus(0);
                dataFile.setServiceKey(serviceKey);
                if (mFile.getSize() <= maxDiskSize) {
                    dataFile.setData(mFile.getBytes());
                }
                blobService.insertBlob(dataFile);
                dataFile.setData(null);

                if (mFile.getSize() > maxDiskSize) {
                    FileUtils.save(fileName, inputStream);
                    logger.debug(fileName + " save ok.");
                }

                if (StringUtils.equalsIgnoreCase(responseType, "json")) {
                    StringBuilder json = new StringBuilder();
                    json.append("{");
                    json.append("'");
                    json.append("fileId");
                    json.append("':'");
                    json.append(fileId);
                    json.append("'");
                    Enumeration<String> pNames = request.getParameterNames();
                    String pName;
                    while (pNames.hasMoreElements()) {
                        json.append(",");
                        pName = (String) pNames.nextElement();
                        json.append("'");
                        json.append(pName);
                        json.append("':'");
                        json.append(request.getParameter(pName));
                        json.append("'");
                    }
                    json.append("}");
                    logger.debug(json.toString());
                    response.getWriter().write(json.toString());
                } else {
                    out.print(fileId);
                }
            }
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        IOUtils.close(inputStream);
    }
}

From source file:com.artivisi.belajar.restful.ui.controller.ApplicationConfigController.java

@RequestMapping(value = "/config/upload", method = RequestMethod.POST)
@ResponseBody//from ww w  . j a v a2s .  c  o  m
public List<Map<String, String>> testUpload(
        @RequestParam(value = "uploadedfiles[]") List<MultipartFile> daftarFoto) throws Exception {

    logger.debug("Jumlah file yang diupload {}", daftarFoto.size());

    List<Map<String, String>> hasil = new ArrayList<Map<String, String>>();

    for (MultipartFile multipartFile : daftarFoto) {
        logger.debug("Nama File : {}", multipartFile.getName());
        logger.debug("Nama File Original : {}", multipartFile.getOriginalFilename());
        logger.debug("Ukuran File : {}", multipartFile.getSize());

        Map<String, String> keterangan = new HashMap<String, String>();
        keterangan.put("Nama File", multipartFile.getOriginalFilename());
        keterangan.put("Ukuran File", Long.valueOf(multipartFile.getSize()).toString());
        keterangan.put("Content Type", multipartFile.getContentType());
        keterangan.put("UUID", UUID.randomUUID().toString());
        File temp = File.createTempFile("xxx", "xxx");
        multipartFile.transferTo(temp);
        keterangan.put("MD5", createMD5Sum(temp));
        hasil.add(keterangan);
    }

    return hasil;
}

From source file:com.ylife.goods.model.UploadImgUpyun.java

/**
 * ??// w ww.  j a v a 2 s .  c  o  m
 * 
 * @param muFile
 * @return Map?oldimgsmall?
 */
public Map<String, String> uploadForOldAndSmall(MultipartFile muFile, UpyunConf upConf) {
    Map<String, String> imgMap = new HashMap<String, String>();
    if (muFile != null && muFile.getSize() != 0) {
        // ??java?
        @SuppressWarnings("unused")
        boolean flag = false;

        // ???????????
        String fileNamess = UploadImgCommon.getPicNamePathSuffix();

        File file = new File(fileNamess);
        try {
            muFile.transferTo(file);
            if (upConf != null) {
                YunBean yb = new YunBean();
                yb.setBucketName(upConf.getBucketName());
                yb.setPassword(upConf.getPassWord());
                yb.setUserName(upConf.getUserName());
                UpYunUtil.yunUp(fileNamess, UploadImgCommon.prefix, yb, UploadImgCommon.suffix);
                // ??
                //LOGGER.debug(LOGGERINFO1 + upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix);
                imgMap.put(OLDIMG, upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix);

                // ???
                //LOGGER.debug("==========56?" + upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix + "!" + SMALL);
                imgMap.put("small",
                        upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix + "!" + SMALL);

            } else {
                flag = true;
            }
        } catch (IllegalStateException e) {
            //LOGGER.error(LOGGERINFO4, e);
            flag = true;
        } catch (IOException e) {
            //LOGGER.error(LOGGERINFO4, e);
            flag = true;
        } catch (Exception e) {
            //LOGGER.error(LOGGERINFO4, e);
            flag = true;
        }
        return imgMap;
    } else {
        return null;
    }
}

From source file:com.glaf.mail.web.springmvc.MailTaskController.java

@RequestMapping("/uploadMails")
public ModelAndView uploadMails(HttpServletRequest request, ModelMap modelMap) {
    MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
    Map<String, Object> params = RequestUtils.getParameterMap(req);
    logger.debug(params);//from  w  w  w  . j a v a 2  s .c om
    // System.out.println(params);
    String taskId = req.getParameter("taskId");
    if (StringUtils.isEmpty(taskId)) {
        taskId = req.getParameter("id");
    }
    MailTask mailTask = null;
    if (StringUtils.isNotEmpty(taskId)) {
        mailTask = mailTaskService.getMailTask(taskId);
    }

    if (mailTask != null && StringUtils.equals(RequestUtils.getActorId(request), mailTask.getCreateBy())) {

        try {
            Map<String, MultipartFile> fileMap = req.getFileMap();
            Set<Entry<String, MultipartFile>> entrySet = fileMap.entrySet();
            for (Entry<String, MultipartFile> entry : entrySet) {
                MultipartFile mFile = entry.getValue();
                if (mFile.getOriginalFilename() != null && mFile.getSize() > 0) {
                    logger.debug(mFile.getName());
                    if (mFile.getOriginalFilename().endsWith(".txt")) {
                        byte[] bytes = mFile.getBytes();
                        String rowIds = new String(bytes);
                        List<String> addresses = StringTools.split(rowIds);
                        if (addresses.size() <= 100000) {
                            mailDataFacede.saveMails(taskId, addresses);
                        } else {
                            throw new RuntimeException("mail addresses too many");
                        }
                        break;
                    }
                }
            }
        } catch (Exception ex) {// ?
            ex.printStackTrace();
            throw new RuntimeException(ex.getMessage());
        }
    }
    return this.mailList(request, modelMap);
}

From source file:com.ylife.goods.model.UploadImgUpyun.java

/**
 * ????/*from   ww  w .ja v  a 2 s .c om*/
 * 
 * @param muFile
 * @return Map?4oldimg0??1?2
 */
public Map<String, String> uploadForABCSize(MultipartFile muFile, UpyunConf upConf) {
    Map<String, String> imgMap = new HashMap<String, String>();
    if (muFile != null && muFile.getSize() != 0) {
        // ??java?
        @SuppressWarnings("unused")
        boolean flag = false;

        // ???????????
        String fileNamess = UploadImgCommon.getPicNamePathSuffix();

        File file = new File(fileNamess);
        try {
            muFile.transferTo(file);
            if (upConf != null) {
                YunBean yb = new YunBean();
                yb.setBucketName(upConf.getBucketName());
                yb.setPassword(upConf.getPassWord());
                yb.setUserName(upConf.getUserName());
                UpYunUtil.yunUp(fileNamess, UploadImgCommon.prefix, yb, UploadImgCommon.suffix);
                // ??
                //LOGGER.debug(LOGGERINFO1 + upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix);
                imgMap.put(OLDIMG, upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix);

                // ??85
                int[] widths = UploadImgCommon.getImgSetOut85(imageSetMapper.queryImageSet());
                UploadImgCommon.sortWidth(widths);
                for (int i = 0; i < widths.length; i++) {
                    // ??
                    //LOGGER.debug(LOGGERINFO2 + widths[i] + LOGGERINFO3 + upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix + "!" + widths[i]);
                    imgMap.put(i + "", upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix
                            + "!" + widths[i]);
                }

            } else {
                flag = true;
            }
        } catch (IllegalStateException e) {
            //LOGGER.error(LOGGERINFO4, e);
            flag = true;
        } catch (IOException e) {
            //LOGGER.error(LOGGERINFO4, e);
            flag = true;
        } catch (Exception e) {
            // LOGGER.error(LOGGERINFO4, e);
            flag = true;
        }
        return imgMap;
    } else {
        return null;
    }
}

From source file:com.ylife.goods.model.UploadImgUpyun.java

/**
 * ????//from   www .jav  a 2  s  .c  om
 * 
 * @param muFile
 * @return Map?key
 */
public Map<String, String> uploadForAllSize(MultipartFile muFile, UpyunConf upConf) {
    Map<String, String> imgMap = new HashMap<String, String>();
    if (muFile != null && muFile.getSize() != 0) {
        // ??java?
        @SuppressWarnings("unused")
        boolean flag = false;

        // ???????????
        String fileNamess = UploadImgCommon.getPicNamePathSuffix();

        File file = new File(fileNamess);
        try {
            muFile.transferTo(file);
            if (upConf != null) {
                YunBean yb = new YunBean();
                yb.setBucketName(upConf.getBucketName());
                yb.setPassword(upConf.getPassWord());
                yb.setUserName(upConf.getUserName());
                UpYunUtil.yunUp(fileNamess, UploadImgCommon.prefix, yb, UploadImgCommon.suffix);
                // ??
                //LOGGER.debug(LOGGERINFO1 + upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix);
                imgMap.put(OLDIMG, upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix);

                // ??
                int[] widths = UploadImgCommon.getImgSet(imageSetMapper.queryImageSet());
                UploadImgCommon.sortWidth(widths);
                for (int i = 0; i < widths.length; i++) {
                    // ??
                    //LOGGER.debug(LOGGERINFO2 + widths[i] + LOGGERINFO3 + upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix + "!" + widths[i]);
                    imgMap.put(widths[i] + "", upConf.getUrlPath() + UploadImgCommon.prefix
                            + UploadImgCommon.suffix + "!" + widths[i]);
                }

            } else {
                flag = true;
            }
        } catch (IllegalStateException e) {
            //LOGGER.error(LOGGERINFO4, e);
            flag = true;
        } catch (IOException e) {
            //LOGGER.error(LOGGERINFO4, e);
            flag = true;
        } catch (Exception e) {
            //LOGGER.error(LOGGERINFO4, e);
            flag = true;
        }
        return imgMap;
    } else {
        return null;
    }
}

From source file:com.ylife.goods.model.UploadImgUpyun.java

/**
 * ????/*from   ww  w.  j  a  v  a 2s  .  c o m*/
 *
 * @param muFile
 * @return Map?oldimgsmall?
 */
public Map<String, String> testUpYun(MultipartFile muFile, UpyunConf upConf) throws IOException {
    Map<String, String> imgMap = new HashMap<String, String>();
    if (muFile != null && muFile.getSize() != 0) {
        // ???????????
        String fileNamess = UploadImgCommon.getPicNamePathSuffix();
        File file = new File(fileNamess);
        muFile.transferTo(file);
        if (upConf != null) {
            YunBean yb = new YunBean();
            yb.setBucketName(upConf.getBucketName());
            yb.setPassword(upConf.getPassWord());
            yb.setUserName(upConf.getUserName());
            KUpYunUtil.kYunUp(fileNamess, UploadImgCommon.prefix, yb, UploadImgCommon.suffix);
            // ??
            //LOGGER.debug(LOGGERINFO1 + upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix);
            imgMap.put(OLDIMG, upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix);

            // ??
            int[] widths = UploadImgCommon.getImgSet(imageSetMapper.queryImageSet());
            UploadImgCommon.sortWidth(widths);
            for (int i = 0; i < widths.length; i++) {
                // ??
                //LOGGER.debug(LOGGERINFO2 + widths[i] + LOGGERINFO3 + upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix + "!" + widths[i]);
                imgMap.put(widths[i] + "", upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix
                        + "!" + widths[i]);
            }
        }
        return imgMap;
    } else {
        return null;
    }
}

From source file:csns.util.FileIO.java

public File save(MultipartFile uploadedFile, User user, File parent, boolean isPublic) {
    if (uploadedFile.isEmpty())
        return null;

    File file = new File();
    file.setName(uploadedFile.getOriginalFilename());
    file.setType(uploadedFile.getContentType());
    file.setSize(uploadedFile.getSize());
    file.setOwner(user);/*from   w w  w .  j av a 2  s .com*/
    file.setParent(parent);
    file.setPublic(isPublic);
    file = fileDao.saveFile(file);

    java.io.File diskFile = getDiskFile(file, false);
    try {
        uploadedFile.transferTo(diskFile);
    } catch (Exception e) {
        logger.error("Failed to save uploaded file", e);
    }

    return file;
}

From source file:de.whs.poodle.repositories.FileRepository.java

public int uploadFile(MultipartFile file) throws IOException {
    InputStream in = file.getInputStream();

    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbc.update(con -> {//from www.  j a  v a2 s . com
        PreparedStatement ps = con.prepareStatement(
                "INSERT INTO uploaded_file(data,mimetype,filename) VALUES(?,?,?)", new String[] { "id" });

        ps.setBinaryStream(1, in, file.getSize());
        ps.setString(2, file.getContentType());
        ps.setString(3, file.getOriginalFilename());
        return ps;
    }, keyHolder);

    return keyHolder.getKey().intValue();
}

From source file:demo.admin.controller.UserController.java

@RequestMapping(value = "/saveCompanyPic", method = RequestMethod.POST)
public Object saveCompanyPic(@RequestParam("file") MultipartFile file, HttpServletResponse response)
        throws Exception {
    Map<String, Object> map = new HashMap<>();
    boolean success = false;
    if (file.getSize() / 1000 / 1000 <= 10) {
        response.setContentType("text/html");
        success = true;/*from   ww  w  . j  av a2  s. c  om*/
        map.put("filePath", fileService.uploadPicture(file));
    }
    map.put("success", success);
    return map;
}