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.MxUploadController.java

@RequestMapping("/uploadNow")
public ModelAndView upload(HttpServletRequest request, ModelMap modelMap) {
    LoginContext loginContext = RequestUtils.getLoginContext(request);

    MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
    String type = req.getParameter("type");
    if (StringUtils.isEmpty(type)) {
        type = "0";
    }/*  w  w w  . ja  v  a  2  s .  co  m*/

    String serviceKey = req.getParameter("serviceKey");
    if (StringUtils.isEmpty(serviceKey)) {
        modelMap.put("error_message", "????serviceKey?");
        return new ModelAndView("/error");
    }

    Map<String, Object> paramMap = RequestUtils.getParameterMap(req);
    logger.debug("paramMap:" + paramMap);
    String businessKey = req.getParameter("businessKey");
    String objectId = req.getParameter("objectId");
    String objectValue = req.getParameter("objectValue");
    int status = ParamUtils.getInt(paramMap, "status");
    List<DataFile> dataFiles = new java.util.ArrayList<DataFile>();
    try {
        semaphore.acquire();

        if (StringUtils.isNotEmpty(businessKey)) {
            List<DataFile> rows = blobService.getBlobList(businessKey);
            if (rows != null && rows.size() > 0) {
                dataFiles.addAll(rows);
            }
        }

        paramMap.remove("businessKey");
        paramMap.put("createBy", loginContext.getActorId());
        paramMap.put("serviceKey", serviceKey);
        paramMap.put("status", status);
        BlobItemQuery query = new BlobItemQuery();
        Tools.populate(query, paramMap);

        query.createBy(loginContext.getActorId());
        query.serviceKey(serviceKey);
        query.status(status);
        List<DataFile> rows = blobService.getBlobList(query);
        if (rows != null && rows.size() > 0) {
            Iterator<DataFile> iterator = rows.iterator();
            while (iterator.hasNext()) {
                DataFile dataFile = iterator.next();
                if (!dataFiles.contains(dataFile)) {
                    dataFiles.add(dataFile);
                }
            }
        }

        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) {
                String filename = mFile.getOriginalFilename();
                logger.debug("upload file:" + filename);
                String fileId = UUID32.getUUID();
                if (filename.indexOf("/") != -1) {
                    filename = filename.substring(filename.lastIndexOf("/") + 1, filename.length());
                } else if (filename.indexOf("\\") != -1) {
                    filename = filename.substring(filename.lastIndexOf("\\") + 1, filename.length());
                }
                BlobItem dataFile = new BlobItemEntity();
                dataFile.setLastModified(System.currentTimeMillis());
                dataFile.setCreateBy(loginContext.getActorId());
                dataFile.setFileId(fileId);
                dataFile.setData(mFile.getBytes());
                dataFile.setFilename(filename);
                dataFile.setName(mFile.getName());
                dataFile.setContentType(mFile.getContentType());
                dataFile.setSize((int) mFile.getSize());
                dataFile.setType(type);
                dataFile.setStatus(status);
                dataFile.setObjectId(objectId);
                dataFile.setObjectValue(objectValue);
                dataFile.setServiceKey(serviceKey);
                blobService.insertBlob(dataFile);
                dataFile.setData(null);
                dataFiles.add(dataFile);
            }
        }

        if (dataFiles.size() > 0) {
            modelMap.put("dataFiles", dataFiles);
        }

    } catch (Exception ex) {
        logger.debug(ex);
        return new ModelAndView("/error");
    } finally {
        semaphore.release();
    }

    return this.showUpload(request, modelMap);
}

From source file:com.slience.controller.PictureOfMongoStoreController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody String handleFileUpload(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) {
    if (!file.isEmpty()) {
        try {/*from w  w  w  .  jav  a2  s.  com*/
            //byte[] bytes = file.getBytes();
            //BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(name)));
            //stream.write(bytes);
            //stream.close();

            System.out.println("------------------------>" + file.getName() + ":" + file.getSize());

            return "You successfully uploaded " + name + "!";
        } catch (Exception e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name + " because the file was empty.";
    }
}

From source file:cherry.foundation.async.AsyncFileProcessHandlerImpl.java

/**
 * ?????/*from  ww w .  ja v  a 2s  .co m*/
 *
 * @param launcherId ?????ID
 * @param description 
 * @param file ??
 * @param handlerName ????????Bean?????Bean?{@link FileProcessHandler}???????
 * @param args 
 * @return ??????ID
 */
@Override
public long launchFileProcess(String launcherId, String description, MultipartFile file, String handlerName,
        String... args) {

    long asyncId = asyncProcessStore.createFileProcess(launcherId, bizDateTime.now(), description,
            file.getName(), file.getOriginalFilename(), file.getContentType(), file.getSize(), handlerName,
            args);
    try {

        File tempFile = createFile(file);

        Map<String, String> message = new HashMap<>();
        message.put(ASYNCID, String.valueOf(asyncId));
        message.put(FILE, tempFile.getAbsolutePath());
        message.put(NAME, file.getName());
        message.put(ORIGINAL_FILENAME, file.getOriginalFilename());
        message.put(CONTENT_TYPE, file.getContentType());
        message.put(SIZE, String.valueOf(file.getSize()));
        message.put(HANDLER_NAME, handlerName);
        for (int i = 0; i < args.length; i++) {
            message.put(String.valueOf(i), args[i]);
        }
        jmsOperations.convertAndSend(message, messagePostProcessor);

        asyncProcessStore.updateToLaunched(asyncId, bizDateTime.now());
        return asyncId;
    } catch (IOException ex) {
        asyncProcessStore.finishWithException(asyncId, bizDateTime.now(), ex);
        throw new IllegalStateException(ex);
    }
}

From source file:org.aksw.gerbil.web.FileUploadController.java

@RequestMapping(value = "upload", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<UploadFileContainer> upload(MultipartHttpServletRequest request,
        HttpServletResponse response) {/*from   w  w  w  .  j  av  a2  s. c o m*/

    if (path == null) {
        logger.error("Path must be not null");
        return new ResponseEntity<UploadFileContainer>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    LinkedList<FileMeta> files = new LinkedList<FileMeta>();
    MultipartFile mpf = null;

    for (Iterator<String> it = request.getFileNames(); it.hasNext();) {
        mpf = request.getFile(it.next());
        logger.debug("{} uploaded", mpf.getOriginalFilename());

        FileMeta fileContainer = new FileMeta();
        fileContainer.setName(mpf.getOriginalFilename());
        fileContainer.setSize(mpf.getSize() / 1024 + "Kb");
        fileContainer.setFileType(mpf.getContentType());

        try {
            fileContainer.setBytes(mpf.getBytes());
            createFolderIfNotExists();
            FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(path + mpf.getOriginalFilename()));

        } catch (IOException e) {
            logger.error("Error during file upload", e);
            fileContainer.setError(e.getMessage());
        }
        files.add(fileContainer);
    }

    UploadFileContainer uploadFileContainer = new UploadFileContainer(files);
    return new ResponseEntity<UploadFileContainer>(uploadFileContainer, HttpStatus.OK);
}

From source file:io.lavagna.web.api.CardDataController.java

private boolean ensureFileSize(List<MultipartFile> files) {
    Integer maxSizeInByte = NumberUtils
            .createInteger(configurationRepository.getValueOrNull(Key.MAX_UPLOAD_FILE_SIZE));
    if (maxSizeInByte == null) {
        return true;
    }/*from w w w  .  j ava 2  s.  c  o  m*/
    for (MultipartFile file : files) {
        if (file.getSize() > maxSizeInByte) {
            return false;
        }
    }
    return true;
}

From source file:gateway.controller.util.GatewayUtil.java

/**
 * Handles the uploaded file from the data/file endpoint. This will push the file to S3, and then modify the content
 * of the job to reference the new S3 location of the file.
 * /*from  w  w  w .  ja  v  a2 s.  co m*/
 * @param jobId
 *            The Id of the Job, used for generating a unique S3 bucket file name.
 * @param job
 *            The ingest job, containing the DataResource metadata
 * @param file
 *            The file to be uploaded
 * @return The modified job, with the location of the S3 file added to the metadata
 */
public IngestJob pushS3File(String jobId, IngestJob job, MultipartFile file)
        throws AmazonServiceException, AmazonClientException, IOException {
    // The content length must be specified.
    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentLength(file.getSize());
    // Send the file to S3. The key corresponds with the S3 file name.
    String fileKey = String.format("%s-%s", jobId, file.getOriginalFilename());
    s3Client.putObject(AMAZONS3_BUCKET_NAME, fileKey, file.getInputStream(), metadata);
    // Note the S3 file path in the Ingest Job.
    // Attach the file to the FileLocation object
    FileLocation fileLocation = new S3FileStore(AMAZONS3_BUCKET_NAME, fileKey, file.getSize(), AMAZONS3_DOMAIN);
    ((FileRepresentation) job.getData().getDataType()).setLocation(fileLocation);
    logger.log(String.format("S3 File for Job %s Persisted to %s:%s", jobId, AMAZONS3_BUCKET_NAME, fileKey),
            PiazzaLogger.INFO);
    return job;
}

From source file:com.jayway.restassured.examples.springmvc.controller.FileUploadController.java

@RequestMapping(value = "/fileUploadWithParam", method = POST, consumes = MULTIPART_FORM_DATA_VALUE, produces = APPLICATION_JSON_VALUE)
public @ResponseBody FileWithParam fileUploadWithParam(@RequestParam(value = "controlName") MultipartFile file,
        @RequestParam(value = "param", required = false) String param) throws IOException {
    FileDescription fd1 = new FileDescription();
    fd1.setContent(new String(file.getBytes()));
    fd1.setName(file.getName());/*  w  w  w . ja v a 2  s.co  m*/
    fd1.setMimeType(file.getContentType());
    fd1.setOriginalName(file.getOriginalFilename());
    fd1.setSize(file.getSize());

    FileWithParam fileWithParam = new FileWithParam();
    fileWithParam.setFile(fd1);
    fileWithParam.setParam(param);

    return fileWithParam;
}

From source file:com.jayway.restassured.examples.springmvc.controller.FileUploadController.java

@RequestMapping(value = "/multiFileUpload", method = POST, consumes = MULTIPART_FORM_DATA_VALUE, produces = APPLICATION_JSON_VALUE)
public @ResponseBody List<FileDescription> multiFileUpload(
        @RequestParam(value = "controlName1") MultipartFile file1,
        @RequestParam(value = "controlName2") MultipartFile file2) throws IOException {
    FileDescription fd1 = new FileDescription();
    fd1.setContent(new String(file1.getBytes()));
    fd1.setName(file1.getName());//ww  w .j a  va  2s.  co  m
    fd1.setMimeType(file1.getContentType());
    fd1.setOriginalName(file1.getOriginalFilename());
    fd1.setSize(file1.getSize());

    FileDescription fd2 = new FileDescription();
    fd2.setContent(new String(file2.getBytes()));
    fd2.setName(file2.getName());
    fd2.setMimeType(file2.getContentType());
    fd2.setOriginalName(file2.getOriginalFilename());
    fd2.setSize(file2.getSize());
    return asList(fd1, fd2);
}

From source file:com.sammyun.service.impl.FileServiceImpl.java

public boolean isValid(FileType fileType, MultipartFile multipartFile) {
    if (multipartFile == null) {
        return false;
    }//from  w w  w . j  a  v  a2 s  .  c om
    Setting setting = SettingUtils.get();
    if (setting.getUploadMaxSize() != null && setting.getUploadMaxSize() != 0
            && multipartFile.getSize() > setting.getUploadMaxSize() * 1024L * 1024L) {
        return false;
    }
    String[] uploadExtensions;
    if (fileType == FileType.flash) {
        uploadExtensions = setting.getUploadFlashExtensions();
    } else if (fileType == FileType.media) {
        uploadExtensions = setting.getUploadMediaExtensions();
    } else if (fileType == FileType.file) {
        uploadExtensions = setting.getUploadFileExtensions();
    } else {
        uploadExtensions = setting.getUploadImageExtensions();
    }
    if (ArrayUtils.isNotEmpty(uploadExtensions)) {
        String originalFilename = multipartFile.getOriginalFilename();
        return FilenameUtils.isExtension(originalFilename.toLowerCase(), uploadExtensions);
    }
    return false;
}

From source file:net.groupbuy.service.impl.FileServiceImpl.java

public boolean isValid(FileType fileType, MultipartFile multipartFile) {
    if (multipartFile == null) {
        return false;
    }//  w  w w  . ja v a  2s . co m
    Setting setting = SettingUtils.get();
    if (setting.getUploadMaxSize() != null && setting.getUploadMaxSize() != 0
            && multipartFile.getSize() > setting.getUploadMaxSize() * 1024L * 1024L) {
        return false;
    }
    String[] uploadExtensions;
    if (fileType == FileType.flash) {
        uploadExtensions = setting.getUploadFlashExtensions();
    } else if (fileType == FileType.media) {
        uploadExtensions = setting.getUploadMediaExtensions();
    } else if (fileType == FileType.file) {
        uploadExtensions = setting.getUploadFileExtensions();
    } else {
        uploadExtensions = setting.getUploadImageExtensions();
    }
    if (ArrayUtils.isNotEmpty(uploadExtensions)) {
        return FilenameUtils.isExtension(multipartFile.getOriginalFilename(), uploadExtensions);
    }
    return false;
}