當前位置: 首頁>>代碼示例>>Java>>正文


Java MultipartFile.getSize方法代碼示例

本文整理匯總了Java中org.springframework.web.multipart.MultipartFile.getSize方法的典型用法代碼示例。如果您正苦於以下問題:Java MultipartFile.getSize方法的具體用法?Java MultipartFile.getSize怎麽用?Java MultipartFile.getSize使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.springframework.web.multipart.MultipartFile的用法示例。


在下文中一共展示了MultipartFile.getSize方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: add

import org.springframework.web.multipart.MultipartFile; //導入方法依賴的package包/類
public void add(Weaver weaver,MultipartFile data) { // 회원 추가 서비스
	Pass pass;
	if(weaverDao.existsWeaver())
		pass = new Pass("ROLE_USER"); 
	else
		pass = new Pass("ROLE_ADMIN"); // 최초 회원 가입시 운영자 지위
	weaver.addPass(pass);
	weaver.setPassword(passwordEncoder.encodePassword(weaver.getPassword(), null));
	
	if(data != null && data.getSize()>0)
		weaver.setData(dataDao.insert(new Data(new ObjectId(new Date()).toString(), data, weaver)));
	weaverDao.insert(weaver);	
	
	File file = new File(gitUtil.getGitPath() + weaver.getId());
	file.mkdir();
}
 
開發者ID:forweaver,項目名稱:forweaver2.0,代碼行數:17,代碼來源:WeaverService.java

示例2: validate

import org.springframework.web.multipart.MultipartFile; //導入方法依賴的package包/類
public void validate(Object obj, Errors errors) {

        FileUpload fileUploadModel = (FileUpload) obj;
        MultipartFile file = fileUploadModel.getFile();
        if(file.isEmpty()){
            errors.rejectValue("file", "upload.file.required");
        }
        else if(!PNG_MIME_TYPE_PNG.equalsIgnoreCase(file.getContentType()) && !PNG_MIME_TYPE_JPEG.equalsIgnoreCase(file.getContentType())){
            errors.rejectValue("file", "upload.invalid.file.type");
        }

        else if(file.getSize() > A_MB_IN_BYTES){
            errors.rejectValue("file", "upload.exceeded.file.size");
        }

    }
 
開發者ID:Exercon,項目名稱:AntiSocial-Platform,代碼行數:17,代碼來源:FileValidator.java

示例3: uploadAvatar

import org.springframework.web.multipart.MultipartFile; //導入方法依賴的package包/類
@ApiOperation("頭像上傳")
@PostMapping("/profile/avatar")
@RequiresAuthentication
public ResponseEntity uploadAvatar(@RequestParam("file") MultipartFile file) throws IOException {

    int uid = SessionHelper.get().getUid();

    if (file.getSize()/1000 > 2*1024) {
        throw new WebErrorException("文件過大");
    }

    if (! file.getContentType().equals("image/jpeg")) {
        throw new WebErrorException("文件格式非法");
    }
    String filePath = fileUtil.uploadAvatar(file.getInputStream(), "jpg");

    if (filePath == null) {
        throw new WebErrorException("文件上傳失敗");
    }

    int aid = attachmentService.add(uid, filePath);
    if (! userService.updateUserAvatar(uid, aid)) {
        throw new WebErrorException("頭像更新失敗");
    }
    return new ResponseEntity("頭像更新成功");
}
 
開發者ID:Eagle-OJ,項目名稱:eagle-oj-api,代碼行數:27,代碼來源:UserController.java

示例4: uploadNote

import org.springframework.web.multipart.MultipartFile; //導入方法依賴的package包/類
@RequestMapping(value = "/uploadNote")
@ResponseBody
public String uploadNote(@RequestParam(value = "uploadFile") MultipartFile uploadFile, @RequestParam(value = "notebookId") int notebookId, HttpSession session) throws IOException  {
     int userId = getUserId();
     JsonObject json = new JsonObject();

     if (uploadFile.getSize() > 0) {
         String leftPath = session.getServletContext().getRealPath("/temp/");
         String filename = uploadFile.getOriginalFilename();
         if (filename.endsWith("html")) {
             File file = new File(leftPath, filename);
             uploadFile.transferTo(file);
             createNoteService.uploadFileNote(userId, notebookId, file, new Date());
             file.delete();
             json.addProperty("result", "success");
         } else {
             json.addProperty("result", "wrongType");
         }
     } else {
         json.addProperty("result", "noFile");
     }
    return json.toString();
}
 
開發者ID:qinjr,項目名稱:TeamNote,代碼行數:24,代碼來源:NoteController.java

示例5: isValidImage

import org.springframework.web.multipart.MultipartFile; //導入方法依賴的package包/類
public static String isValidImage(HttpServletRequest request, MultipartFile file){
    //最大文件大小
    long maxSize = 5242880;
    //定義允許上傳的文件擴展名
    HashMap<String, String> extMap = new HashMap<String, String>();
    extMap.put("image", "gif,jpg,jpeg,png,bmp");

    if(!ServletFileUpload.isMultipartContent(request)){
        return "請選擇文件";
    }

    if(file.getSize() > maxSize){
        return "上傳文件大小超過5MB限製";
    }
    //檢查擴展名
    String fileName=file.getOriginalFilename();
    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
    if(!Arrays.<String>asList(extMap.get("image").split(",")).contains(fileExt)){
        return "上傳文件擴展名是不允許的擴展名\n隻允許" + extMap.get("image") + "格式";
    }

    return "valid";
}
 
開發者ID:Exrick,項目名稱:xmall,代碼行數:24,代碼來源:QiniuUtil.java

示例6: isValid

import org.springframework.web.multipart.MultipartFile; //導入方法依賴的package包/類
@Override
public boolean isValid(MultipartFile[] multipartFiles, ConstraintValidatorContext constraintValidatorContext) {
    long _totalSize = 0L;
    if (multipartFiles == null || multipartFiles.length <= 0) {
        return allowEmpty;
    }
    boolean result = false;
    for (MultipartFile multipartFile : multipartFiles) {
        result = (allowSize(multipartFile) && allowContentType(multipartFile));
        if (!result) {
            return false;
        }
        _totalSize += multipartFile.getSize();
    }
    /*
      totalSize = 0 ,則不限製
      如果超出大小,則限製
     */
    return totalSize == 0 || _totalSize < totalSize;
}
 
開發者ID:egzosn,項目名稱:spring-jdbc-orm,代碼行數:21,代碼來源:MultipartFilesUploadValidate.java

示例7: put

import org.springframework.web.multipart.MultipartFile; //導入方法依賴的package包/類
/**
* <B>方法名稱:</B>文件上傳<BR>
* <B>概要說明:</B>文件上傳<BR>
* @param key 鍵值
* @param type 類型
* @param userId 用戶標識
* @param mf 文件對象	
* @param expired 過期時間
* @param descInfo 描述
* @return String 錯誤信息
* @throws Exception 輸入輸出異常
*/
  public JSONObject put(String key, String type, String userId, MultipartFile mf, Date expired, String descInfo) throws Exception {
      
  	String filename = mf.getOriginalFilename();
  	String extName = getExtName(filename);
  	String fileId = FastDFSClientUtils.upload(mf.getBytes(), extName);
  	String dataGroup = fileId.substring(0,fileId.indexOf("/"));
  	long bytes = mf.getSize();
  	
      SysFile file = new SysFile();
      file.setKey(key);
      file.setName(filename);
      file.setType(type);
      file.setExt(extName);
      file.setBytes(bytes);
      file.setDataPath(FASTDFS_BASEURL + fileId);
      file.setDataGroup(dataGroup);
      file.setExpired(expired);
      file.setDescInfo(descInfo);
      file.setUpdateBy(userId);
      sysFileComDao.insert(file);
      
      JSONObject ret = new JSONObject();
      ret.put("success", true);
      ret.put("key", key);
      ret.put("type", type);
      ret.put("name", mf.getOriginalFilename());
      ret.put("bytes", mf.getSize());
      ret.put("dataPath", FASTDFS_BASEURL + fileId);
      ret.put("dataGroup", dataGroup);
      ret.put("expired", expired);
      return ret;
  }
 
開發者ID:craware,項目名稱:webapp-tyust,代碼行數:45,代碼來源:SysFileComService.java

示例8: update

import org.springframework.web.multipart.MultipartFile; //導入方法依賴的package包/類
public void update(Weaver weaver,String password,String newpassword,String say,MultipartFile data) { // 회원 수정
	// TODO Auto-generated method stub
	if(data != null && data.getSize() > 0) {
		dataDao.delete(weaver.getData());
		weaver.setData(dataDao.insert(new Data(new ObjectId(new Date()).toString(), data, weaver)));
	}

	if(this.validPassword(weaver,password) && newpassword != null && newpassword.length() > 3)
		weaver.setPassword(passwordEncoder.encodePassword(newpassword, null));

	if(say != null && !say.equals(""))
		weaver.setSay(say);

	weaverDao.update(weaver);
}
 
開發者ID:forweaver,項目名稱:forweaver2.0,代碼行數:16,代碼來源:WeaverService.java

示例9: upload

import org.springframework.web.multipart.MultipartFile; //導入方法依賴的package包/類
@RequestMapping("upload/{id}")
public ExecuteResult<Boolean> upload(@RequestParam("file") MultipartFile[] multipartFiles, @PathVariable Long id)
		throws IOException {

	final ExecuteResult<Boolean> result = new ExecuteResult<>();
	
	try {
		for (MultipartFile file : multipartFiles) {
			String fileName = file.getOriginalFilename();
			if (file.getSize() > Constants.MAX_FILE_SIZE) {
				result.setSuccess(false);
				return result;
			}

			String realPath = new Date().getTime() + fileName.substring(fileName.lastIndexOf("."));
			String type = FileUtil.isImage(file.getInputStream()) ? Attach.UPLOAD_TYPE_IMAGE
					: Attach.UPLOAD_TYPE_FILE;
			File tempFile = new File(upload_dir + realPath);
			if (!tempFile.getParentFile().exists()) {
				tempFile.mkdirs();
			}
			FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(tempFile));
			Attach attach = new Attach(id, fileName, type, realPath, new Date());
			attachDao.save(attach);
		}
		result.setSuccess(true);
	} catch (final Exception e) {
		result.setSuccess(false);
		result.setErrorCode(ErrorCode.EXCEPTION.name());
		logger.error("", e);
	}
	return result;
}
 
開發者ID:handexing,項目名稱:pinkyLam-Blog-Server,代碼行數:34,代碼來源:FileController.java

示例10: DocumentContentVersion

import org.springframework.web.multipart.MultipartFile; //導入方法依賴的package包/類
public DocumentContentVersion(StoredDocument item, MultipartFile file, Blob data) {
    this.mimeType = file.getContentType();
    setOriginalDocumentName(file.getOriginalFilename());
    this.size = file.getSize();
    this.documentContent = new DocumentContent(this, data);
    this.storedDocument = item;
}
 
開發者ID:hmcts,項目名稱:document-management-store-app,代碼行數:8,代碼來源:DocumentContentVersion.java

示例11: isValid

import org.springframework.web.multipart.MultipartFile; //導入方法依賴的package包/類
@Override
public boolean isValid(MultipartFile multipartFile, ConstraintValidatorContext constraintValidatorContext) {

    System.out.println(multipartFile.getContentType());
    if (multipartFile == null || multipartFile.getSize() == 0) {
        return allowEmpty;
    }

    return (allowSize(multipartFile) && allowContentType(multipartFile));

}
 
開發者ID:egzosn,項目名稱:spring-jdbc-orm,代碼行數:12,代碼來源:SingleFileUploadValidate.java

示例12: UploadEntityImp

import org.springframework.web.multipart.MultipartFile; //導入方法依賴的package包/類
/**
 * 帶文件大小限製的構造
 * 
 * @param file
 *            MultipartFile
 * @param maxSize2KB
 *            限製文件大小
 * @throws IOException
 */
public UploadEntityImp(MultipartFile file, long maxSizeByKB) throws MaxUploadSizeExceededException {

	this.file = file;

	if (file == null) {
		throw new NullPointerException("MultipartFil 不能為空!");
	}

	fileSizeByKB = file.getSize() / 1024;

	if (fileSizeByKB > maxSizeByKB) {
		throw new MaxUploadSizeExceededException(maxSizeByKB * 1024);
	}
	
	// 獲取該文件的文件名
	originalFilename = file.getOriginalFilename();

	// 獲取文件後綴
	fileSuffix = UploadUtil.getFileSuffix(originalFilename);
	if (fileSuffix == null || fileSuffix.length() == 0) {
		// 通過Mime類型獲取文件類型
		fileSuffix = ContentTypeUtil.getFileTypeByMimeType(file.getContentType());
	}

	// 創建文件名
	filename = UploadUtil.getFileName();


}
 
開發者ID:ZiryLee,項目名稱:FileUpload2Spring,代碼行數:39,代碼來源:UploadEntityImp.java

示例13: createContent

import org.springframework.web.multipart.MultipartFile; //導入方法依賴的package包/類
@PostMapping("/objects")
@Timed
public ResponseEntity<String> createContent(@RequestParam(required = false) Integer size,
    @RequestParam("file") MultipartFile multipartFile)
    throws URISyntaxException {
    if (multipartFile.getSize() > applicationProperties.getMaxAvatarSize()) {
        throw new BusinessException(ERR_VALIDATION,
            "Avatar file must not exceed " + applicationProperties.getMaxAvatarSize() + " bytes");
    }
    String result = storageRepository.store(multipartFile, size);
    return ResponseEntity.ok(result);
}
 
開發者ID:xm-online,項目名稱:xm-ms-entity,代碼行數:13,代碼來源:StorageResource.java

示例14: arrangement

import org.springframework.web.multipart.MultipartFile; //導入方法依賴的package包/類
@ResponseBody
@RequestMapping("/arrangement")
public CommonResult arrangement(MultipartFile multipartFile, Homework homework, HttpSession session) {
    if (multipartFile == null)
        return new CommonResult("文件為空", false);
    else if (homework.getCourseClassId() == null)
        return new CommonResult("班級為空", false);
    else if (!FileFormatUtils.isPackage(multipartFile.getOriginalFilename()))
        return new CommonResult("文件格式不是壓縮包", false);
    else if (multipartFile.getSize() > FILE_SIZE)
        return new CommonResult("文件大小超出限製", false);
    else if (StringUtils.isEmpty(homework.getHomeworkName(), homework.getContent()))
        return new CommonResult("作業名稱或正文不能為空", false);
    else {
        if (homework.getHomeworkName().length() > TITLE_SIZE) {
            if (homework.getContent().length() > CONTENT_SIZE)
                return new CommonResult("作業名稱和正文太長", false);
            else
                return new CommonResult("作業名稱太長", false);
        } else if (homework.getContent().length() > CONTENT_SIZE)
            return new CommonResult("正文太長", false);
    }

    User user = (User)session.getAttribute("user");
    homework.setAnnouncerId(user.getId());
    if (homeworkService.arrangement(homework, multipartFile)) {
        return new CommonResult("成功", true);
    } else
        return new CommonResult("添加作業失敗", false);
}
 
開發者ID:Topview-us,項目名稱:school-website,代碼行數:31,代碼來源:HomeworkController.java

示例15: doPost

import org.springframework.web.multipart.MultipartFile; //導入方法依賴的package包/類
public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
  // Check that we have a file upload request
  boolean isMultipart = ServletFileUpload.isMultipartContent(request);
  if (!isMultipart) {
    return;
  }
  try {
    MultipartHttpServletRequest
        multiRequest =
        new CommonsMultipartResolver().resolveMultipart(request);
    MultiValueMap<String, MultipartFile> fileMap = multiRequest.getMultiFileMap();
    BlobstoreService blobstoreService = AppFactory.get().getBlobstoreService();
    Map<String, String> names = new HashMap<>(1);
    for (String fieldName : fileMap.keySet()) {
      MultipartFile file = fileMap.getFirst(fieldName);
      String fileName = file.getOriginalFilename();
      String contentType = file.getContentType();
      long sizeInBytes = file.getSize();
      String
          blobKey =
          blobstoreService.store(fileName, contentType, sizeInBytes, file.getInputStream());
      names.put(fieldName, blobKey);
      names.put("file", fileName);

    }
    response.getWriter().write(new Gson().toJson(names));
    response.setStatus(HttpStatus.SC_CREATED);
  } catch (Exception ex) {
    _logger.severe("Upload failed", ex);
  }
}
 
開發者ID:logistimo,項目名稱:logistimo-web-service,代碼行數:33,代碼來源:DirectFileUploadServlet.java


注:本文中的org.springframework.web.multipart.MultipartFile.getSize方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。