Java Code Examples for org.springframework.web.multipart.commons.CommonsMultipartFile

The following examples show how to use org.springframework.web.multipart.commons.CommonsMultipartFile. These examples are extracted from open source projects. 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 Project: yfs   Source File: FileController.java    License: Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "upload file")
@ResponseBody
@RequestMapping(value = "api/file", method = {RequestMethod.POST})
public Result upload(MultipartFile file, HttpServletRequest httpServletRequest) {
    Result result = new Result();
    Pair<String, FileEvent> pair = null;
    try {
        CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) file;
        pair = FileService.store(clusterProperties, commonsMultipartFile, httpServletRequest);
        boolean qosResult = EventService.create(clusterProperties, yfsConfig, pair, clusterProperties.getStore().getNode().size() / 2 + 1);
        if (qosResult == true) {
            result.setCode(ResultCode.C200.code);
        } else {
            result.setCode(ResultCode.C202.code);
        }
        result.setValue(pair.getKey());
        logger.debug("Success to upload {}", pair.getKey());
    } catch (Exception e) {
        logger.error("Upload", e);
        if (pair != null)
            FileService.delete(clusterProperties, pair.getKey());
        result.setCode(ResultCode.C500.getCode());
        result.setValue(ResultCode.C500.getDesc());
    }
    return result;
}
 
Example 2
Source Project: classchecks   Source File: ClockinAsStudentController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 
* @Title: doClockIn 
* @Description: 学生在教师拍照考勤时,没有检测到自己考勤
* @return
* BasicEntityVo<?>
 */
@RequestMapping("/clock-in")
@ResponseBody
public BasicEntityVo<?> doClockIn(String jwAccount, String loginAccount, 
		Double lng, Double lat, @RequestParam("clockinImg")CommonsMultipartFile file) {
	if(StringUtils.isBlank(jwAccount)) {
		return new BasicEntityVo<>(StudentClockInBusinessCode.JW_ACCOUNT_EMPTY[0], StudentClockInBusinessCode.JW_ACCOUNT_EMPTY[1]);
	}
	if(StringUtils.isBlank(loginAccount)) {
		return new BasicEntityVo<>(StudentClockInBusinessCode.LOGIN_ACCOUNT_EMPTY[0], StudentClockInBusinessCode.LOGIN_ACCOUNT_EMPTY[1]);
	}
	if(lng == 0.0 || null == lng || lat == 0.0 || null == lat) {
		return new BasicEntityVo<>(StudentClockInBusinessCode.LNG_LAT_EMPTY[0], StudentClockInBusinessCode.LNG_LAT_EMPTY[1]);
	}
	if(file.isEmpty()) {
		return new BasicEntityVo<>(StudentClockInBusinessCode.BUSSINESS_IMAGE_EMPTY[0], StudentClockInBusinessCode.BUSSINESS_IMAGE_EMPTY[1]);
	}
	
	return clockinAsStudentService.clockin(jwAccount, loginAccount, lng, lat, file);
}
 
Example 3
/**
 * This method converts the uploaded files into a map where the key is the
 * file name and the value is the file content.
 */
public static synchronized Map<String, String> convertFilesToMap(CommonsMultipartFile[] fileInputList ) {
    Map<String, String> fileMap = new LinkedHashMap<String, String>();
    CommonsMultipartFile tmpMultiFile;
    String tmpCharset;
    fileNameCounterMap.clear();
    for (int i = 0; i < fileInputList.length; i++) {
        tmpMultiFile = fileInputList[i];
        try {
            if (tmpMultiFile != null && !tmpMultiFile.isEmpty() && tmpMultiFile.getInputStream() != null) {
                tmpCharset = CrawlUtils.extractCharset(tmpMultiFile.getInputStream());
                fileMap.put(
                        getFileName(tmpMultiFile.getOriginalFilename()),
                        tmpMultiFile.getFileItem().getString(tmpCharset));
            }
        } catch (IOException e) {}
    }
    return fileMap;
}
 
Example 4
@RequestMapping(value = "/file/upload/{uploadId}", method = RequestMethod.POST)
@ResponseBody
public FileDto upload(@PathVariable String uploadId,
	@RequestParam("data") CommonsMultipartFile multipart, HttpServletRequest request,
	HttpServletResponse response) {
	OutputStream out = null;
	InputStream in = null;
	try {
		out = this.store.write(uploadId, multipart.getOriginalFilename(), multipart.getContentType());
		in = multipart.getInputStream();
		IOUtils.copy(in, out);
		return this.store.getFileBean(uploadId);
	} catch (IOException e) {
		throw new RuntimeException(e.getMessage(), e);
	} finally {
		IOUtils.closeQuietly(in);
		IOUtils.closeQuietly(out);
	}
}
 
Example 5
Source Project: jeewx-boot   Source File: MyJwWebJwidController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * url转变为 MultipartFile对象
 * @param url
 * @param fileName
 * @return
 * @throws Exception
 */
private static MultipartFile createFileItem(String url, String fileName) throws Exception{
 FileItem item = null;
 try {
	 HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
	 conn.setReadTimeout(30000);
	 conn.setConnectTimeout(30000);
	 //设置应用程序要从网络连接读取数据
	 conn.setDoInput(true);
	 conn.setRequestMethod("GET");
	 if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
		 InputStream is = conn.getInputStream();

		 FileItemFactory factory = new DiskFileItemFactory(16, null);
		 String textFieldName = "uploadfile";
		 item = factory.createItem(textFieldName, ContentType.APPLICATION_OCTET_STREAM.toString(), false, fileName);
		 OutputStream os = item.getOutputStream();

		 int bytesRead = 0;
		 byte[] buffer = new byte[8192];
		 while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
			 os.write(buffer, 0, bytesRead);
		 }
		 os.close();
		 is.close();
	 }
 } catch (IOException e) {
	 throw new RuntimeException("文件下载失败", e);
 }

 return new CommonsMultipartFile(item);
}
 
Example 6
Source Project: Project   Source File: ProductManagerController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 处理图片
 *
 * @param request
 * @param productImgList
 * @return
 * @throws IOException
 */
private ImageHolder handleImage(HttpServletRequest request, List<ImageHolder> productImgList) throws IOException {
    MultipartHttpServletRequest multipartHttpServletRequest =
            (MultipartHttpServletRequest) request;
    ImageHolder thumbnail = null;

    // 取出缩略图并构建 ImageHolder 对象
    CommonsMultipartFile thumbnailFile =
            (CommonsMultipartFile) multipartHttpServletRequest.getFile("thumbnail");
    thumbnail = new ImageHolder(thumbnailFile.getInputStream(),
            thumbnailFile.getOriginalFilename());
    // 取出详情图列表并构建List<ImageHolder>列表对象,最多支持6张图片上传
    for (int i = 0; i < IMAGE_MAX_UPDATE_COUNT; i++) {
        CommonsMultipartFile productImgFile =
                (CommonsMultipartFile) multipartHttpServletRequest.getFile("productImg" + i);
        if (productImgFile != null) {
            // 若取出的详情图片文件流不为空,则将其加入详情图列表
            ImageHolder productImg = new ImageHolder(productImgFile.getInputStream(),
                    productImgFile.getOriginalFilename());
            productImgList.add(productImg);
        } else {
            // 若取出的详情图片文件流为空,则终止循环
            break;
        }
    }
    return thumbnail;
}
 
Example 7
Source Project: TIL   Source File: Service.java    License: MIT License 5 votes vote down vote up
/**
 * 게시물/문의사항 등록
 * @param article
 * @return
 */
public int insertArticle(Article article) {
	Long artcSeq = commonMapper.selectNextval("sq_article");
	article.setArtcSeq(artcSeq);
	// 첨부파일 업로드 처리
	CommonsMultipartFile attach = article.getAttach();
	if (attach != null && !attach.isEmpty()) {
		String path = File.separator + "upload" + File.separator + "article_" + serviceMode + File.separator
				+ artcSeq + File.separator;
		// 디렉토리 생성
		File dir = new File(serverRootPath + path);
		if (!dir.exists()) {
			dir.mkdirs();
		}

		String fileName = attach.getOriginalFilename();
		String ext = "";
		if (fileName.indexOf(".") >= 0) {
			ext = fileName.substring(fileName.lastIndexOf("."));
		}
		fileName = UUID.randomUUID().toString().replaceAll("-", "") + ext;

		try {
			attach.transferTo(new File(serverRootPath + path + fileName));
			article.setFileName(path + fileName);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	return articleMapper.insert(article);
}
 
Example 8
Source Project: super-cloudops   Source File: CodesAnalyzerController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Submitted analyzing assets file for java.
 * 
 * @param file
 * @return
 * @throws Exception
 */
@PostMapping("java")
public RespBase<?> submitJavaAnalyzer(@RequestParam("assetFile") CommonsMultipartFile file,
		@RequestBody SpotbugsAnalysingModel model) throws Exception {
	if (log.isInfoEnabled()) {
		log.info("Analyzing assetFile for spotbugs-java: {}", model);
	}
	RespBase<Object> resp = RespBase.create();

	file.transferTo(new File("/mnt/disk1/ci-analyzer/data/assetFiles/" + model.getProjectName()));

	adapter.forAdapt(AnalyzerKind.SPOTBUGS).analyze(model);
	return resp;
}
 
Example 9
Source Project: spring-boot   Source File: RotateImgUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 选择图片
 *
 * @param fileName 上传的文件
 */
public static final InputStream rotateImg(MultipartFile fileName) throws TSException {
    if (fileName == null) return null;
    CommonsMultipartFile cf = (CommonsMultipartFile) fileName;
    DiskFileItem fi = (DiskFileItem) cf.getFileItem();
    File file = fi.getStoreLocation();
    //获取旋转角度
    int angle = getRotateAngle(file);
    //选择图片
    return rotatePhonePhoto(file, angle);
}
 
Example 10
Source Project: classchecks   Source File: RegisterServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
	@Transactional(readOnly = false, rollbackFor = RuntimeException.class)
	public BasicVo register(String phone, String smscode, String regID, CommonsMultipartFile[] files) {
		// 检测数据库是否已有记录,这里检查是防止用户获取验证码成功后,更换一个已有的手机号输入
		boolean hasPhone = smsCodeMapper.hasPhoneRegistered(phone).length > 0 ? true : false;
		if(hasPhone) {
			return new BasicVo(RegisterBusinessCode.BUSSINESS_PHONE_EXIST[0], RegisterBusinessCode.BUSSINESS_PHONE_EXIST[1]);
		}
		
		// 调用短信接口验证输入的短信验证码是否可用
		boolean isVerify = SMSUtil.verifySmsCode(phone, smscode);
		
		if(isVerify) {
			BasicVo basicVo = null;
			try {
				SecurityAccountVo secAcc = new SecurityAccountVo();
				secAcc.setSecurityAccount(phone);
				secAcc.setSecuritSmsCode(smscode);
				secAcc.setRegID(regID);
				secAcc.setSecuritType(Student_User_Type);
//				// 插入数据
				registerMapper.saveRegisterInfo(secAcc);
				secAcc = registerMapper.findAccountByPhone(phone);
				LOG.info("secAcc="+secAcc);
				fileSave(files, phone); // 保存上传的图片到临时位置
				// 图片预处理
				rawFaceProc(ImgStoragePath.RAW_FACE_IMG_SAVE_PATH+File.separator+phone,
						ImgStoragePath.PROC_FACE_IMG_SAVE_PATH+File.separator+phone, secAcc.getFaceLabel());
				// 生成CSV标签
				generateCSV(ImgStoragePath.PROC_FACE_IMG_SAVE_PATH+File.separator+phone, ImgStoragePath.CSV_FILE_SAVE_PATH);
				basicVo = new BasicVo(RegisterBusinessCode.BUSINESS_SUCCESS[0], RegisterBusinessCode.BUSINESS_SUCCESS[1]);
			} catch(Exception e) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				basicVo = new BasicVo(RegisterBusinessCode.BUSSINESS_FAILED[0], RegisterBusinessCode.BUSSINESS_FAILED[1]);
				LOG.error("学生注册错误", e);
			}
			return basicVo;
		}
		return new BasicVo(RegisterBusinessCode.BUSSINESS_SMS_ERROR[0], RegisterBusinessCode.BUSSINESS_SMS_ERROR[1]);
	}
 
Example 11
/**
 * Control whether the uploaded files are of HTML type and whether their
 * size is under the maxFileSize limit.
 *
 * @param uploadAuditSetUpCommand
 * @param errors
 */
private void validateFiles(AuditSetUpCommand uploadAuditSetUpCommand, Errors errors) {
    boolean emptyFile = true;
    Metadata metadata = new Metadata();
    MimeTypes mimeTypes = TikaConfig.getDefaultConfig().getMimeRepository();
    String mime;

    for (int i=0;i<uploadAuditSetUpCommand.getFileInputList().length;i++ ) {
        try {
            CommonsMultipartFile cmf = uploadAuditSetUpCommand.getFileInputList()[i];
            if (cmf.getSize() > maxFileSize) {
                Long maxFileSizeInMega = maxFileSize / 1000000;
                String[] arg = {maxFileSizeInMega.toString()};
                errors.rejectValue(ID_INPUT_FILE_PREFIX + "[" + i + "]", FILE_SIZE_EXCEEDED_MSG_BUNDLE_KEY, arg, "{0}");
            }
            if (cmf.getSize() > 0) {
                emptyFile = false;
                mime = mimeTypes.detect(new BufferedInputStream(cmf.getInputStream()), metadata).toString();
                LOGGER.debug("mime  " + mime + "  " +cmf.getOriginalFilename());
                if (!authorizedMimeType.contains(mime)) {
                    errors.rejectValue(ID_INPUT_FILE_PREFIX + "[" + i + "]", NOT_HTML_MSG_BUNDLE_KEY);
                }
            }
        } catch (IOException ex) {
            LOGGER.warn(ex);
            errors.rejectValue(ID_INPUT_FILE_PREFIX + "[" + i + "]", NOT_HTML_MSG_BUNDLE_KEY);
        }
    }
    if(emptyFile) { // if no file is uploaded
        LOGGER.debug("emptyFiles");
        errors.rejectValue(GENERAL_ERROR_MSG_KEY,
                NO_FILE_UPLOADED_MSG_BUNDLE_KEY);
    }
}
 
Example 12
private MultipartFile createMultipartFile(String filename) throws IOException {
  File file = new File("/src/test/resources/" + filename);

  DiskFileItem fileItem =
      new DiskFileItem(
          "file", "text/plain", false, file.getName(), (int) file.length(), file.getParentFile());
  fileItem.getOutputStream();
  return new CommonsMultipartFile(fileItem);
}
 
Example 13
Source Project: oslits   Source File: EgovMultipartResolver.java    License: GNU General Public License v3.0 4 votes vote down vote up
/**
    * multipart에 대한 parsing을 처리한다.
    */
   @SuppressWarnings("rawtypes")
@Override
   protected MultipartParsingResult parseFileItems(List fileItems, String encoding) {

   //스프링 3.0변경으로 수정한 부분
   MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();
Map<String, String[]> multipartParameters = new HashMap<String, String[]>();

// Extract multipart files and multipart parameters.
for (Iterator<?> it = fileItems.iterator(); it.hasNext();) {
    FileItem fileItem = (FileItem)it.next();

    if (fileItem.isFormField()) {

	String value = null;
	if (encoding != null) {
	    try {
		value = fileItem.getString(encoding);
	    } catch (UnsupportedEncodingException ex) {
	    	LOGGER.warn("Could not decode multipart item '{}' with encoding '{}': using platform default"
	    			, fileItem.getFieldName(), encoding);
		value = fileItem.getString();
	    }
	} else {
	    value = fileItem.getString();
	}
	String[] curParam = (String[])multipartParameters.get(fileItem.getFieldName());
	if (curParam == null) {
	    // simple form field
	    multipartParameters.put(fileItem.getFieldName(), new String[] { value });
	} else {
	    // array of simple form fields
	    String[] newParam = StringUtils.addStringToArray(curParam, value);
	    multipartParameters.put(fileItem.getFieldName(), newParam);
	}
    } else {
    	
	if (fileItem.getSize() > 0) {
	    // multipart file field
	    CommonsMultipartFile file = new CommonsMultipartFile(fileItem);

	    //스프링 3.0 업그레이드 API변경으로인한 수정
	    List<MultipartFile> fileList = new ArrayList<MultipartFile>();
	    fileList.add(file);

	    if (multipartFiles.put(fileItem.getName(), fileList) != null) { // CHANGED!!
	    	throw new MultipartException("Multiple files for field name [" + file.getName() + "] found - not supported by MultipartResolver");
	    }
	}

    }
}

return new MultipartParsingResult(multipartFiles, multipartParameters, null);
   }
 
Example 14
Source Project: uccn   Source File: TestFastDfs.java    License: Apache License 2.0 4 votes vote down vote up
private static MultipartFile getMulFileByPath(String picPath) {
    FileItem fileItem = createFileItem(picPath);
    MultipartFile mfile = new CommonsMultipartFile(fileItem);
    return mfile;
}
 
Example 15
Source Project: classchecks   Source File: ClockinAsTeacherServiceImpl.java    License: Apache License 2.0 4 votes vote down vote up
private boolean fileSave(CommonsMultipartFile img, String savePath, String longTime) {
	return SaveImageUtils.saveImage(img, savePath, longTime+".jpg");
}
 
Example 16
Source Project: classchecks   Source File: ClockinAsStudentServiceImpl.java    License: Apache License 2.0 4 votes vote down vote up
private boolean fileSave(CommonsMultipartFile img, String savePath, String longTime) {
	return SaveImageUtils.saveImage(img, savePath, longTime+".jpg");
}
 
Example 17
Source Project: classchecks   Source File: ClockinAsStudentServiceImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public BasicEntityVo<?> clockin(String jwAccount, String loginAccount, Double lng, Double lat,
		CommonsMultipartFile file) {
	
	LOG.info("学生端考勤Service");
	LOG.info("ContentType:" + file.getContentType() 
		+ " Filename:" + file.getOriginalFilename() + " Size:" + file.getSize());
	LOG.info("学生上传经纬度:lng=" + lng + " lat:" + lat);
	Integer teacherUId = clockinAsStudentMapper.getTeacherIDByStudentClock(jwAccount, 500);
	
	LOG.info("教师UID:" + teacherUId);
	SchoolCourseClockModel sccm = basicService.getSchoolCourseClockModelNow();
	PointVo gpsPoint = clockinAsStudentMapper.getGPSByTeacherID(teacherUId, sccm);
	LOG.info("教师最新考勤记录的GPS坐标:" + gpsPoint);
	
	double stuDistanceTea = PositionUtil.distance(gpsPoint.getLng(), gpsPoint.getLat(), lng, lat);
	
	LOG.info("学生与教师的距离:" + stuDistanceTea);
	
	if(stuDistanceTea > 550) {
		return new BasicEntityVo<>(StudentClockInBusinessCode.GPS_DISTANCE_GT_50[0], StudentClockInBusinessCode.GPS_DISTANCE_GT_50[1]);
	}
	
	Date date = new Date();
	// "yyyy-MM-dd"字符串
	String dtSimpleDate = DateUtil.dtSimpleFormat(date);
	// "yyyyMMddHHmmss"日期字符串
	String longTime = DateUtil.longDate(date);
	// 保存文件路径的每个文件夹名称数组,教师上传的图片以每天的日期作为文件夹
	String [] pathKey = {ImgStoragePath.STUDENT_CLOCK_IN_IMG_PATH, loginAccount, dtSimpleDate};
	// 保存图片的文件夹路径
	String dirSavePath = FileUtils.buildFilePath(pathKey);
	
	boolean isSaved = fileSave(file, dirSavePath, longTime);
	if(isSaved == false) { // 上传的图片保存失败
		return new BasicEntityVo<>(StudentClockInBusinessCode.BUSSINESS_IMAGE_SAVE_FAILED[0], StudentClockInBusinessCode.BUSSINESS_IMAGE_SAVE_FAILED[1]);
	}
	
	String absolutePath = FileUtils.buildFilePath(dirSavePath, longTime+".jpg");
	Mat imgSrc = Imgcodecs.imread(absolutePath, Imgcodecs.CV_LOAD_IMAGE_GRAYSCALE); // 加载上传的图片
	
	Mat procMat = PreProcessFace.smallProcessedFace(imgSrc);
	
	if(null == procMat) {
		return new BasicEntityVo<>(StudentClockInBusinessCode.BUSSINESS_NO_DETECT_FACE[0], StudentClockInBusinessCode.BUSSINESS_NO_DETECT_FACE[1]);
	}
	
	String collecteFaceRoute = FileUtils.buildFilePath(ImgStoragePath.PROC_FACE_IMG_SAVE_PATH, loginAccount);
	
	List<Mat> collectedMats = new ArrayList<Mat>();
	List<Integer> faceLabels = new ArrayList<Integer>();
	CSVFileUtils.loadImage(collecteFaceRoute, collectedMats, faceLabels);
	
	// 将人脸标签放入一个Mat对象,OpenCV提供的人脸识别算法中接收一个存有人脸标签的Mat
	Mat labelsMat = new Mat(faceLabels.size(), 1, CvType.CV_32SC1, new Scalar(0));
	for(int i = 0; i < faceLabels.size(); i ++) {
		labelsMat.put(i, 0, new int[]{faceLabels.get(i)});
	}
	
	// 训练人脸模型,这里使用的是特征脸算法
	BasicFaceRecognizer faceModel = Recognition.learnCollectedFaces(collectedMats, labelsMat);
	
	Mat reconstructedFace = Recognition.reconstructFace(faceModel, procMat);
	double similarity = Recognition.getSimilarity(reconstructedFace, procMat);
	LOG.info("similarity = " + similarity);
	LOG.info("predict_label: "+faceModel.predict_label(procMat));
	
	if(similarity > 0.13) {
		return new BasicEntityVo<>(StudentClockInBusinessCode.FACE_NON_EXISTENT[0], 
				StudentClockInBusinessCode.FACE_NON_EXISTENT[1]);
	}
	
	// 学生自己考勤成功后更新考勤记录
	clockinAsStudentMapper.updateStudentClockinRecord(jwAccount);
	
	StudentClockinVo vo = new StudentClockinVo();
	
	vo.setStuName(clockinAsStudentMapper.findStudentName(jwAccount));
	vo.setCurTime(DateUtil.hmsFormat(new Date()));
	// TODO 更新考勤记录
	return new BasicEntityVo<>(StudentClockInBusinessCode.BUSINESS_SUCCESS[0], 
			StudentClockInBusinessCode.BUSINESS_SUCCESS[1], vo);
}
 
Example 18
/**
 * 
 * @param addScenarioCommand
 * @param errors 
 * @return  whether the scenario handled by the current AddScenarioCommand
 * has a correct type and size
 */
public boolean checkScenarioFileTypeAndSize(
        AddScenarioCommand addScenarioCommand, 
        Errors errors) {
    if (addScenarioCommand.getScenarioFile() == null) { // if no file uploaded
        LOGGER.debug("empty Scenario File");
        errors.rejectValue(GENERAL_ERROR_MSG_KEY,
                MANDATORY_FIELD_MSG_BUNDLE_KEY);
        errors.rejectValue(SCENARIO_FILE_KEY,
                NO_SCENARIO_UPLOADED_MSG_BUNDLE_KEY);
        return false;
    }
    Metadata metadata = new Metadata();
    MimeTypes mimeTypes = TikaConfig.getDefaultConfig().getMimeRepository();
    String mime;
    try {
        CommonsMultipartFile cmf = addScenarioCommand.getScenarioFile();
        if (cmf.getSize() > maxFileSize) {
            Long maxFileSizeInMega = maxFileSize / 1000000;
            String[] arg = {maxFileSizeInMega.toString()};
            errors.rejectValue(GENERAL_ERROR_MSG_KEY,
                    MANDATORY_FIELD_MSG_BUNDLE_KEY);
            errors.rejectValue(SCENARIO_FILE_KEY, FILE_SIZE_EXCEEDED_MSG_BUNDLE_KEY, arg, "{0}");
            return false;
        } else if (cmf.getSize() > 0) {
            mime = mimeTypes.detect(new BufferedInputStream(cmf.getInputStream()), metadata).toString();
            LOGGER.debug("mime  " + mime + "  " + cmf.getOriginalFilename());
            if (!authorizedMimeType.contains(mime)) {
                errors.rejectValue(GENERAL_ERROR_MSG_KEY,
                    MANDATORY_FIELD_MSG_BUNDLE_KEY);
                errors.rejectValue(SCENARIO_FILE_KEY, NOT_SCENARIO_MSG_BUNDLE_KEY);
                return false;
            }
        } else {
            LOGGER.debug("File with size null");
            errors.rejectValue(GENERAL_ERROR_MSG_KEY,
                MANDATORY_FIELD_MSG_BUNDLE_KEY);
            errors.rejectValue(SCENARIO_FILE_KEY,
                NO_SCENARIO_UPLOADED_MSG_BUNDLE_KEY);
            return false;
        }
    } catch (IOException ex) {
        LOGGER.warn(ex);
        errors.rejectValue(SCENARIO_FILE_KEY, NOT_SCENARIO_MSG_BUNDLE_KEY);
        errors.rejectValue(GENERAL_ERROR_MSG_KEY,
                MANDATORY_FIELD_MSG_BUNDLE_KEY);
        return false;
    }
    return true;
}
 
Example 19
public CommonsMultipartFile getScenarioFile() {
    return scenarioFile;
}
 
Example 20
public void setScenarioFile(final CommonsMultipartFile scenarioFile) {
    this.scenarioFile = scenarioFile;
}
 
Example 21
public CommonsMultipartFile[] getFileInputList() {
    if (fileInputList == null) {
        fileInputList = new CommonsMultipartFile[DEFAULT_LIST_SIZE];
    }
    return fileInputList;
}
 
Example 22
public void setFileInputList(final CommonsMultipartFile[] fileInputList) {
    this.fileInputList = fileInputList.clone();
}
 
Example 23
@Override
protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) {
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();
    Map<String, String> multipartParameterContentTypes = new HashMap<String, String>();

    // Extract multipart files and multipart parameters.
    for (FileItem fileItem : fileItems) {
        if (fileItem.isFormField()) {
            String value;
            String partEncoding = determineEncoding(fileItem.getContentType(), encoding);
            if (partEncoding != null) {
                try {
                    value = fileItem.getString(partEncoding);
                }
                catch (UnsupportedEncodingException ex) {
                    if (log.isWarnEnabled()) {
                        log.warn("Could not decode multipart item '" + fileItem.getFieldName() +
                                "' with encoding '" + partEncoding + "': using platform default");
                    }
                    value = fileItem.getString();
                }
            }
            else {
                value = fileItem.getString();
            }
            String[] curParam = multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] {value});
            }
            else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
            multipartParameterContentTypes.put(fileItem.getFieldName(), fileItem.getContentType());
        }
        else {
            // multipart file field
            CommonsMultipartFile file = new CommonsMultipartFile(fileItem);
            multipartFiles.add(fileItem.getName(), file);
            if (log.isDebugEnabled()) {
                log.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize() +
                        " bytes with original filename [" + file.getOriginalFilename() + "], stored " +
                        file.getStorageDescription());
            }
        }
    }
    return new MultipartParsingResult(multipartFiles, multipartParameters, multipartParameterContentTypes);
}
 
Example 24
@Override
protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) {
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();
    Map<String, String> multipartParameterContentTypes = new HashMap<String, String>();

    // Extract multipart files and multipart parameters.
    for (FileItem fileItem : fileItems) {
        if (fileItem.isFormField()) {
            String value;
            String partEncoding = determineEncoding(fileItem.getContentType(), encoding);
            if (partEncoding != null) {
                try {
                    value = fileItem.getString(partEncoding);
                }
                catch (UnsupportedEncodingException ex) {
                    if (log.isWarnEnabled()) {
                        log.warn("Could not decode multipart item '" + fileItem.getFieldName() +
                                "' with encoding '" + partEncoding + "': using platform default");
                    }
                    value = fileItem.getString();
                }
            }
            else {
                value = fileItem.getString();
            }
            String[] curParam = multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] {value});
            }
            else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
            multipartParameterContentTypes.put(fileItem.getFieldName(), fileItem.getContentType());
        }
        else {
            // multipart file field
            CommonsMultipartFile file = new CommonsMultipartFile(fileItem);
            multipartFiles.add(fileItem.getName(), file);
            if (log.isDebugEnabled()) {
                log.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize() +
                        " bytes with original filename [" + file.getOriginalFilename() + "], stored " +
                        file.getStorageDescription());
            }
        }
    }
    return new MultipartParsingResult(multipartFiles, multipartParameters, multipartParameterContentTypes);
}
 
Example 25
Source Project: odo   Source File: Upload.java    License: Apache License 2.0 4 votes vote down vote up
public CommonsMultipartFile getFileData() {
    return this.fileData;
}
 
Example 26
Source Project: odo   Source File: Upload.java    License: Apache License 2.0 4 votes vote down vote up
public void setFileData(CommonsMultipartFile fileData) {
    this.fileData = fileData;
}
 
Example 27
Source Project: classchecks   Source File: RegisterServiceImpl.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * 
* @Title: fileSave 
* @Description: 对用户上传的图片上进行保存 
* @param files
* @param phone
* void 
* @throws
 */
private void fileSave(CommonsMultipartFile[] files, String phone) {
	String savePath = ImgStoragePath.RAW_FACE_IMG_SAVE_PATH + File.separator + phone;
	for(int i = 0; i < files.length; i ++) {
		SaveImageUtils.saveImage(files[i], savePath, phone+"_"+(i+1)+".jpg");
	}
}
 
Example 28
Source Project: classchecks   Source File: ClockinAsTeacherController.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * 
* @Title: doClockIn 
* @Description: 教师拍照上传对学生进行考勤
* @return
* BasicEntityListVo<?> 
 */
@RequestMapping("/clock-in")
@ResponseBody
public BasicEntityListVo<?> doClockIn(String jwAccount, String phone, Double longitude, Double latitude, @RequestParam("clockinImg")CommonsMultipartFile file, int byWhat) {
	return clockinAsTeacherService.clockin(jwAccount, phone, longitude, latitude, file);
}
 
Example 29
Source Project: classchecks   Source File: ClockinAsTeacherService.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * 
* @Title: clockin 
* @Description: 教师拍照考勤 
* @param jwAccount
* @param phone
* @param clockinImg
* @return
* BasicEntityListVo<?> 
* @throws
 */
//public BasicEntityListVo<?> clockin(String jwAccount, String phone, Double longitude, Double latitude, CommonsMultipartFile clockinImg, int byWhat);
public BasicEntityListVo<?> clockin(String jwAccount, String phone, Double longitude, Double latitude, CommonsMultipartFile clockinImg);
 
Example 30
Source Project: classchecks   Source File: RegisterController.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * 
* @Title: register 
* @Description: 注册
* @param phone
* @param smscode
* @param regID  极光推送从客户端获取的唯一标识
* @param files
* @return
* BasicVo 
* @throws
 */
@RequestMapping("/register")
@ResponseBody
public BasicVo register(String phone, String smscode, String regID, @RequestParam("files")CommonsMultipartFile[] files) {
	return registerService.register(phone, smscode, regID, files);
}