Java Code Examples for org.springframework.web.multipart.MultipartFile#getSize()

The following examples show how to use org.springframework.web.multipart.MultipartFile#getSize() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Server.java    From feign-form with Apache License 2.0 8 votes vote down vote up
@RequestMapping(path = "/upload/{id}", method = POST)
@ResponseStatus(OK)
public ResponseEntity<Long> upload (@PathVariable("id") Integer id,
                                    @RequestParam("public") Boolean isPublic,
                                    @RequestParam("file") MultipartFile file
) {
  HttpStatus status;
  if (id == null || id != 10) {
    status = LOCKED;
  } else if (isPublic == null || !isPublic) {
    status = FORBIDDEN;
  } else if (file.getSize() == 0) {
    status = I_AM_A_TEAPOT;
  } else if (file.getOriginalFilename() == null || file.getOriginalFilename().trim().isEmpty()) {
    status = CONFLICT;
  } else {
    status = OK;
  }
  return ResponseEntity.status(status).body(file.getSize());
}
 
Example 2
Source File: MultipleFileValidator.java    From Spring-MVC-Blueprints with MIT License 6 votes vote down vote up
@Override
public void validate(Object obj, Errors error) {
	MultipleFilesUploadForm form = (MultipleFilesUploadForm) obj;
	List<MultipartFile> files = form.getFiles();
	boolean isValid = true;
	StringBuilder sb = new StringBuilder("");
	for(MultipartFile file:files)
	{
		if(file.getSize() == 0)
		{
			isValid = false;
			sb.append(file.getOriginalFilename()+" ");
		}
	}
	if(!isValid)
		error.rejectValue("files","error.file.size",new String[]{sb.toString()},"File size limit exceeded");
}
 
Example 3
Source File: FileUploadUtils.java    From RuoYi with Apache License 2.0 6 votes vote down vote up
/**
 * 文件大小校验
 *
 * @param file 上传的文件
 * @return
 * @throws FileSizeLimitExceededException 如果超出最大大小
 */
private static void assertAllowed(MultipartFile file, String[] allowedExtension) throws FileSizeLimitExceededException, InvalidExtensionException {
    long size = file.getSize();
    if (size > DEFAULT_MAX_SIZE) {
        throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
    }
    String filename = file.getOriginalFilename();
    String extension = getExtension(file);
    if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
        if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) {
            throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension, filename);
        } else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) {
            throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension, filename);
        } else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) {
            throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension, filename);
        } else {
            throw new InvalidExtensionException(allowedExtension, extension, filename);
        }
    }
}
 
Example 4
Source File: KeyStoreController.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "import PrivateKey by pem", notes = "import PrivateKey by pem")
@ApiImplicitParams({
        @ApiImplicitParam(name = "userName", value = "user name", dataType = "String"),
        @ApiImplicitParam(name = "p12File", value = ".p12 file of private key", dataType = "MultipartFile"),
        @ApiImplicitParam(name = "p12Password", value = ".p12 file password", dataType = "String")
})
@PostMapping("/importP12")
public BaseResponse importP12PrivateKey(@RequestParam String userName,
                                        @RequestParam MultipartFile p12File,
                                        @RequestParam(required = false, defaultValue = "") String p12Password) throws IOException {
    if (!CommonUtils.notContainsChinese(p12Password)) {
        throw new FrontException(ConstantCode.P12_PASSWORD_NOT_CHINESE);
    }
    if (p12File.getSize() == 0) {
        throw new FrontException(ConstantCode.P12_FILE_ERROR);
    }
    keyStoreService.importKeyStoreFromP12(p12File, p12Password, userName);
    return new BaseResponse(ConstantCode.RET_SUCCESS);
}
 
Example 5
Source File: FileController.java    From sdb-mall with Apache License 2.0 6 votes vote down vote up
@PostMapping("/upload")
@Login
public R upload(@RequestParam("file") MultipartFile file) throws Exception {
    if (file.isEmpty()) {
        throw new RRException("上传文件不能为空");
    }

    Long fileSize = file.getSize();
    if (fileSize > 2048 * 1000) {
        return R.error(ResultEnum.VOLUNTEER_UPLOAD_FILE_BIG);
    }

    //上传文件
    String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
    String url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix);

    //保存文件信息
    SysOss sysOss = new SysOss();
    sysOss.setUrl(url);
    sysOss.setCreateDate(new Date());
    sysOss.save();

    return R.ok().put("url", url);
}
 
Example 6
Source File: ImportGroupsController.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@RequestMapping(path = "/importgroups")
   public String execute(@ModelAttribute("importForm") ImportExcelForm importForm, HttpServletRequest request)
    throws Exception {
importForm.setOrgId(0);
MultipartFile file = importForm.getFile();

// validation
if (file == null || file.getSize() <= 0) {
    return "import/importGroups";
}

String sessionId = SessionManager.getSession().getId();
List results = importService.parseGroupSpreadsheet(file, sessionId);
request.setAttribute("results", results);

return "import/importGroups";
   }
 
Example 7
Source File: UploadController.java    From uexam-mysql with GNU Affero General Public License v3.0 5 votes vote down vote up
@RequestMapping("/image")
@ResponseBody
public RestResponse questionUploadAndReadExcel(HttpServletRequest request) {
    MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartHttpServletRequest.getFile("file");
    long attachSize = multipartFile.getSize();
    String imgName = multipartFile.getOriginalFilename();
    try (InputStream inputStream = multipartFile.getInputStream()) {
        String filePath = fileUpload.uploadFile(inputStream, attachSize, imgName);
        userService.changePicture(getCurrentUser(), filePath);
        return RestResponse.ok(filePath);
    } catch (IOException e) {
        return RestResponse.fail(2, e.getMessage());
    }
}
 
Example 8
Source File: AgentController.java    From youkefu with Apache License 2.0 5 votes vote down vote up
private String processAttachmentFile(MultipartFile file , HttpServletRequest request) throws IOException{
  	String id = null ;
  	if(file.getSize() > 0){			//文件尺寸 限制 ?在 启动 配置中 设置 的最大值,其他地方不做限制
	String fileid = UKTools.md5(file.getBytes()) ;	//使用 文件的 MD5作为 ID,避免重复上传大文件
	if(!StringUtils.isBlank(fileid)){
  			AttachmentFile attachmentFile = new AttachmentFile() ;
  			attachmentFile.setCreater(super.getUser(request).getId());
  			attachmentFile.setOrgi(super.getOrgi(request));
  			attachmentFile.setOrgan(super.getUser(request).getOrgan());
  			attachmentFile.setModel(UKDataContext.ModelType.WEBIM.toString());
  			attachmentFile.setFilelength((int) file.getSize());
  			if(file.getContentType()!=null && file.getContentType().length() > 255){
  				attachmentFile.setFiletype(file.getContentType().substring(0 , 255));
  			}else{
  				attachmentFile.setFiletype(file.getContentType());
  			}
  			File uploadFile = new File(file.getOriginalFilename());
  			if(uploadFile.getName()!=null && uploadFile.getName().length() > 255){
  				attachmentFile.setTitle(uploadFile.getName().substring(0 , 255));
  			}else{
  				attachmentFile.setTitle(uploadFile.getName());
  			}
  			if(!StringUtils.isBlank(attachmentFile.getFiletype()) && attachmentFile.getFiletype().indexOf("image") >= 0){
  				attachmentFile.setImage(true);
  			}
  			attachmentFile.setFileid(fileid);
  			attachementRes.save(attachmentFile) ;
  			FileUtils.writeByteArrayToFile(new File(path , "app/webim/"+fileid), file.getBytes());
  			id = attachmentFile.getId();
	}
}
  	return id  ;
  }
 
Example 9
Source File: UploadServiceImpl.java    From fileServer with Apache License 2.0 5 votes vote down vote up
@Override
public String uploadSlaveFile(String fileName, String prefixName, MultipartFile file) throws ServiceException {

    if (file.getSize() <= 0) {
        throw new ParamException("file is null.");
    }

    if(StringUtils.isEmpty(fileName)){
        throw new ParamException("fileName is null");
    }

    if(StringUtils.isEmpty(prefixName)){
        throw new ParamException("prefixName is null");
    }

    fileValidateService.validateFile(file);

    StorePath storePath = StorePath.praseFromUrl(fileName);

    try {

        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        StorePath slaveFile = storageClient.uploadSlaveFile(storePath.getGroup(),storePath.getPath(),
                file.getInputStream(), file.getSize(),prefixName, ext);

        if(slaveFile==null) {
            throw new ServiceException("upload error.");
        }
        return slaveFile.getFullPath();

    }catch (Exception e){
        throw new ServiceException(e);
    }
}
 
Example 10
Source File: FeignSpringFormEncoder.java    From feign-client-test with MIT License 5 votes vote down vote up
/**
 * Wraps a single {@link MultipartFile} into a {@link HttpEntity} and sets the
 * {@code Content-type} header to {@code application/octet-stream}
 *
 * @param file
 * @return
 */
private HttpEntity<?> encodeMultipartFile(MultipartFile file) {
    HttpHeaders filePartHeaders = new HttpHeaders();
    filePartHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    try {
        Resource multipartFileResource = new MultipartFileResource(file.getOriginalFilename(), file.getSize(), file.getInputStream());
        return new HttpEntity<>(multipartFileResource, filePartHeaders);
    } catch (IOException ex) {
        throw new EncodeException("Cannot encode request.", ex);
    }
}
 
Example 11
Source File: WorkflowProcessDefinitionController.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
@PostMapping(value = "/process/definitions/import", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
public CommonResponseDto importProcessDefinition(@RequestParam("uploadFile") MultipartFile file,
        HttpServletRequest request) {
    if (file == null || file.getSize() <= 0) {
        log.error("invalid file content uploaded");
        throw new WecubeCoreException("Invalid file content uploaded.");
    }

    if (log.isInfoEnabled()) {
        log.info("About to import process definition,filename={},size={}", file.getOriginalFilename(),
                file.getSize());
    }

    try {
        String filedata = IOUtils.toString(file.getInputStream(), Charset.forName("utf-8"));
        String jsonData = new String(StringUtilsEx.decodeBase64(filedata), Charset.forName("utf-8"));
        ProcDefInfoExportImportDto importDto = convertImportData(jsonData);

        String token = request.getHeader("Authorization");

        ProcDefInfoExportImportDto result = procDefService.importProcessDefinition(importDto, token);
        return CommonResponseDto.okayWithData(result);
    } catch (IOException e) {
        log.error("errors while reading upload file", e);
        throw new WecubeCoreException("Failed to import process definition.");
    }

}
 
Example 12
Source File: UKTools.java    From youkefu with Apache License 2.0 5 votes vote down vote up
public static void  processAttachmentFile(MultipartFile[] files, AttachmentRepository attachementRes , String path,User user , String orgi, WorkOrders workOrders, HttpServletRequest request  , String dataid , String modelid) throws IOException{
	if(files!=null && files.length > 0){
		workOrders.setAnonymous(true);//变更用途为是否有 附件
		//保存附件
		for(MultipartFile file : files){
			if(file.getSize() > 0){			//文件尺寸 限制 ?在 启动 配置中 设置 的最大值,其他地方不做限制
				String fileid = UKTools.md5(file.getBytes()) ;	//使用 文件的 MD5作为 ID,避免重复上传大文件
				if(!StringUtils.isBlank(fileid)){
  			AttachmentFile attachmentFile = new AttachmentFile() ;
  			attachmentFile.setCreater(user.getId());
  			attachmentFile.setOrgi(orgi);
  			attachmentFile.setOrgan(user.getOrgan());
  			attachmentFile.setDataid(dataid);
  			attachmentFile.setModelid(modelid);
  			attachmentFile.setModel(UKDataContext.ModelType.WORKORDERS.toString());
  			attachmentFile.setFilelength((int) file.getSize());
  			if(file.getContentType()!=null && file.getContentType().length() > 255){
  				attachmentFile.setFiletype(file.getContentType().substring(0 , 255));
  			}else{
  				attachmentFile.setFiletype(file.getContentType());
  			}
  			if(file.getOriginalFilename()!=null && file.getOriginalFilename().length() > 255){
  				attachmentFile.setTitle(file.getOriginalFilename().substring(0 , 255));
  			}else{
  				attachmentFile.setTitle(file.getOriginalFilename());
  			}
  			if(!StringUtils.isBlank(attachmentFile.getFiletype()) && attachmentFile.getFiletype().indexOf("image") >= 0){
  				attachmentFile.setImage(true);
  			}
  			attachmentFile.setFileid(fileid);
  			attachementRes.save(attachmentFile) ;
  			FileUtils.writeByteArrayToFile(new File(path , "app/workorders/"+fileid), file.getBytes());
				}
			}
		}
		
	}
}
 
Example 13
Source File: FileResourceController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@PostMapping
public WebMessage saveFileResource( @RequestParam MultipartFile file,
    @RequestParam( defaultValue = "DATA_VALUE" ) FileResourceDomain domain
)
    throws WebMessageException, IOException
{
    String filename = StringUtils
        .defaultIfBlank( FilenameUtils.getName( file.getOriginalFilename() ), DEFAULT_FILENAME );

    String contentType = file.getContentType();
    contentType = FileResourceUtils.isValidContentType( contentType ) ? contentType : DEFAULT_CONTENT_TYPE;

    long contentLength = file.getSize();

    log.info( "File uploaded with filename: '{}', original filename: '{}', content type: '{}', content length: {}",
        filename, file.getOriginalFilename(), file.getContentType(), contentLength );

    if ( contentLength <= 0 )
    {
        throw new WebMessageException( WebMessageUtils.conflict( "Could not read file or file is empty." ) );
    }

    ByteSource bytes = new MultipartFileByteSource( file );

    String contentMd5 = bytes.hash( Hashing.md5() ).toString();

    FileResource fileResource = new FileResource( filename, contentType, contentLength, contentMd5, domain );

    File tmpFile = FileResourceUtils.toTempFile( file );

    fileResourceService.saveFileResource( fileResource, tmpFile );

    WebMessage webMessage = new WebMessage( Status.OK, HttpStatus.ACCEPTED );
    webMessage.setResponse( new FileResourceWebMessageResponse( fileResource ) );

    return webMessage;
}
 
Example 14
Source File: FileUploadUtils.java    From LuckyFrameWeb with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 文件大小校验
 *
 * @param file 上传的文件
 * @return
 * @throws FileSizeLimitExceededException 如果超出最大大小
 */
public static final void assertAllowed(MultipartFile file) throws FileSizeLimitExceededException
{
    long size = file.getSize();
    if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE)
    {
        throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
    }
}
 
Example 15
Source File: FileUploadUtils.java    From supplierShop with MIT License 5 votes vote down vote up
/**
 * 文件大小校验
 *
 * @param file 上传的文件
 * @return
 * @throws FileSizeLimitExceededException 如果超出最大大小
 * @throws InvalidExtensionException
 */
public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
        throws FileSizeLimitExceededException, InvalidExtensionException
{
    long size = file.getSize();
    if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE)
    {
        throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
    }

    String fileName = file.getOriginalFilename();
    String extension = getExtension(file);
    if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension))
    {
        if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION)
        {
            throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,
                    fileName);
        }
        else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION)
        {
            throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,
                    fileName);
        }
        else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION)
        {
            throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,
                    fileName);
        }
        else
        {
            throw new InvalidExtensionException(allowedExtension, extension, fileName);
        }
    }

}
 
Example 16
Source File: UploadServiceImpl.java    From cms with Apache License 2.0 4 votes vote down vote up
@Override
public Map<String,Object> upload(String directory,MultipartFile file,ConfigManager conf){
    if (file.isEmpty()) {
        return MapResult.mapError("10");
    }

    String fileName=null;
    long fileSize=0;

    try{
        fileName=file.getOriginalFilename();
        fileSize=file.getSize();
        String  contentType= file.getContentType();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if(!conf.getValue("upload.file.exts").contains(suffix)) {
            return MapResult.mapError("13");
        }
        long maxSize=Long.parseLong(conf.getValue("upload.file.maxSize"));
        if (fileSize >maxSize ) {
            return MapResult.mapError("14","上传的文件大小不能超过[" + maxSize / (1024 * 1024) + "M]");
        }

        String rootPath=conf.getValue("upload.directory");
        String savePath=directory+"/"+PathFormat.parse(conf.getValue("upload.path.format"))+suffix;

        String physicalPath =rootPath +savePath;
        String url=conf.getValue("upload.file.URL")+savePath;
        File targetFile=new File(physicalPath);
        Map<String,Object>  map = valid(targetFile);
        file.transferTo(targetFile);

        map.put( "size", targetFile.length() );
        map.put( "title", targetFile.getName() );
        map.put("url",url);
        map.put("type", suffix);
        map.put("original", fileName);
        return map;

    }catch (Exception e){
        LOG.error("上传文件错误:{}",e.getMessage());
    }
    return MapResult.mapError("15");
}
 
Example 17
Source File: UploadController.java    From uexam with GNU Affero General Public License v3.0 4 votes vote down vote up
@ResponseBody
@RequestMapping("/configAndUpload")
public Object upload(HttpServletRequest request, HttpServletResponse response) {
    String action = request.getParameter("action");
    if (action.equals(IMAGE_UPLOAD)) {
        try {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            MultipartFile multipartFile = multipartHttpServletRequest.getFile(IMAGE_UPLOAD_FILE);
            long attachSize = multipartFile.getSize();
            String imgName = multipartFile.getOriginalFilename();
            String filePath;
            try (InputStream inputStream = multipartFile.getInputStream()) {
                filePath = fileUpload.uploadFile(inputStream, attachSize, imgName);
            }
            String imageType = imgName.substring(imgName.lastIndexOf("."));
            UploadResultVM uploadResultVM = new UploadResultVM();
            uploadResultVM.setOriginal(imgName);
            uploadResultVM.setName(imgName);
            uploadResultVM.setUrl(filePath);
            uploadResultVM.setSize(multipartFile.getSize());
            uploadResultVM.setType(imageType);
            uploadResultVM.setState("SUCCESS");
            return uploadResultVM;
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    } else {
        UeditorConfigVM ueditorConfigVM = new UeditorConfigVM();
        ueditorConfigVM.setImageActionName(IMAGE_UPLOAD);
        ueditorConfigVM.setImageFieldName(IMAGE_UPLOAD_FILE);
        ueditorConfigVM.setImageMaxSize(2048000L);
        ueditorConfigVM.setImageAllowFiles(Arrays.asList(".png", ".jpg", ".jpeg", ".gif", ".bmp"));
        ueditorConfigVM.setImageCompressEnable(true);
        ueditorConfigVM.setImageCompressBorder(1600);
        ueditorConfigVM.setImageInsertAlign("none");
        ueditorConfigVM.setImageUrlPrefix("");
        ueditorConfigVM.setImagePathFormat("");
        return ueditorConfigVM;
    }
    return null;
}
 
Example 18
Source File: FileServiceImpl.java    From albert with MIT License 4 votes vote down vote up
@Override
	public String saveImage(MultipartFile file,String path) {
		
		if(file == null || file.getSize() <= 0){
			return null;
		}
		
		String origFileName = file.getOriginalFilename();
		
		String ext = FilenameUtils.getExtension(origFileName);

		String destPath = getImagePath(ext);
		
		String saveFileName = destPath + "." + ext;
		
		saveFile(file, saveFileName,path);
		
		//小图
		/*String iconFileName = destPath + "_0." + ext;
		
		String base = this.getImageSavePath() + File.separator;
		
		//ImageUtil.zoomImg(base + saveFileName, base + iconFileName, ext.toUpperCase());
*/		
		return saveFileName;
	}
 
Example 19
Source File: FileServiceImpl.java    From efo with MIT License 4 votes vote down vote up
@Override
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
        Exception.class)
public boolean upload(int categoryId, String tag, String description, String prefix, MultipartFile multipartFile,
                      User user) {
    if (user.getIsUploadable() == 1) {
        String name = multipartFile.getOriginalFilename();
        String suffix = FileExecutor.getFileSuffix(name);
        String localUrl = SettingConfig.getUploadStoragePath() + ValueConsts.SEPARATOR + name;
        Category category = categoryService.getById(categoryId);
        long maxSize = Formatter.sizeToLong(EfoApplication.settings.getStringUseEval(ConfigConsts
                .FILE_MAX_SIZE_OF_SETTING));
        long size = multipartFile.getSize();
        boolean fileExists = localUrlExists(localUrl);
        //检测标签是否合法
        if (EfoApplication.settings.getBooleanUseEval(ConfigConsts.TAG_REQUIRE_OF_SETTING)) {
            String[] tags = Checker.checkNull(tag).split(ValueConsts.SPACE);
            if (tags.length <= EfoApplication.settings.getIntegerUseEval(ConfigConsts.TAG_SIZE_OF_SETTING)) {
                int maxLength = EfoApplication.settings.getIntegerUseEval(ConfigConsts.TAG_LENGTH_OF_SETTING);
                for (String t : tags) {
                    if (t.length() > maxLength) {
                        return false;
                    }
                }
            } else {
                return false;
            }
        }
        //是否可以上传
        boolean canUpload = !multipartFile.isEmpty() && size <= maxSize && Pattern.compile(EfoApplication
                .settings.getStringUseEval(ConfigConsts.FILE_SUFFIX_MATCH_OF_SETTING)).matcher(suffix).matches()
                && (Checker.isNotExists(localUrl) || !fileExists || EfoApplication.settings.getBooleanUseEval
                (ConfigConsts.FILE_COVER_OF_SETTING));
        logger.info("is empty [" + multipartFile.isEmpty() + "], file size [" + size + "], max file size [" +
                maxSize + "]");
        if (canUpload) {
            String visitUrl = getRegularVisitUrl(Checker.isNotEmpty(prefix) && user.getPermission() > 1 ? prefix
                    : EfoApplication.settings.getStringUseEval(ConfigConsts.CUSTOM_LINK_RULE_OF_SETTING), user,
                    name, suffix, category);
            if (fileExists) {
                removeByLocalUrl(localUrl);
            }
            if (visitUrlExists(visitUrl)) {
                removeByVisitUrl(visitUrl);
            }
            try {
                multipartFile.transferTo(new java.io.File(localUrl));
                logger.info("local url of upload file: " + localUrl);
                File file = new File(name, suffix, localUrl, visitUrl, WebUtils.scriptFilter(description),
                        WebUtils.scriptFilter(tag), user.getId(), categoryId);
                int[] auth = SettingConfig.getAuth(ConfigConsts.FILE_DEFAULT_AUTH_OF_SETTING);
                file.setAuth(auth[0], auth[1], auth[2], auth[3], auth[4]);
                boolean isSuccess = fileDAO.insertFile(file);
                if (isSuccess) {
                    long fileId = fileDAO.getIdByLocalUrl(localUrl);
                    if (fileId > 0) {
                        authService.insertDefaultAuth(user.getId(), fileId);
                    }
                } else {
                    FileExecutor.deleteFile(localUrl);
                }
                return isSuccess;
            } catch (Exception e) {
                FileExecutor.deleteFile(localUrl);
                logger.error("save file error: " + e.getMessage());
            }
        }
    }
    return false;
}
 
Example 20
Source File: HeritFileUploadUtil.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
     * HERE
     * @param request
     * @param where
     * @param maxFileSize
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static List<HeritFormBasedFileVO> filesUpload(HttpServletRequest request, String where, long maxFileSize) throws Exception {
    	List<HeritFormBasedFileVO> list = new ArrayList<HeritFormBasedFileVO>();

		MultipartHttpServletRequest mptRequest = (MultipartHttpServletRequest)request;
		Iterator fileIter = mptRequest.getFileNames();

		//System.out.println("in");
		
		while (fileIter.hasNext()) {
		    MultipartFile mFile = mptRequest.getFile((String)fileIter.next());
		    //if (mFile.getSize() == 0) {
		    //	continue;
		    //}
		    
		    HeritFormBasedFileVO vo = new HeritFormBasedFileVO();

		    String tmp = mFile.getOriginalFilename();
		    //System.out.println("Orifilename : "+tmp);
		    //System.out.println("filename : "+mFile.getName());
            if (tmp.lastIndexOf("\\") >= 0) {
            	tmp = tmp.substring(tmp.lastIndexOf("\\") + 1);
            }

            vo.setFieldName(mFile.getName());
            vo.setFileName(tmp);
            vo.setContentType(mFile.getContentType());
            //서브디렉토리 주석처리
//	            vo.setServerSubPath(getTodayString());
            vo.setPhysicalName(getPhysicalFileName());
            vo.setSize(mFile.getSize());
            //System.out.println("size : " + mFile.getSize());

            if (tmp.lastIndexOf(".") >= 0) {
       	 		vo.setPhysicalName(vo.getPhysicalName());	// 2012.11 KISA 보안조치
            }

            if (mFile.getSize() > 0) {
            	InputStream is = null;
            	//System.out.println("size : " + mFile.getSize());
            	try {
            		is = mFile.getInputStream();
//	            		saveFile(is, new File(HeritWebUtil.filePathBlackList(where+SEPERATOR+vo.getServerSubPath()+SEPERATOR+vo.getPhysicalName())));
            		
            		//저장되는 이름 제어
            		saveFile(is, new File(HeritWebUtil.filePathBlackList(where+SEPERATOR+vo.getFileName())));
            		//System.out.println("saveFile Name : "+vo.getFileName());
            	} catch(Exception e){
            		e.printStackTrace();
            	} finally {
            		if (is != null) {
            			is.close();
            		}
            	}
            }
        	list.add(vo);
		}

		return list;
    }