利用原生的 file input上传 图片

public void addPic(@RequestParam(value = "pic", required = false)MultipartFile pic) throws IOException {
		if (pic != null) {
			if (FileUtil.isAllowUpImg(pic.getOriginalFilename())) {
				InputStream stream=null;
				try {
					stream=pic.getInputStream();
				} catch (Exception e) {
					e.printStackTrace();
				}
				String subFolder = "adv";//路径中添加的一个字符串
				String fileName=pic.getOriginalFilename();
				if(stream==null){
					throw new IllegalArgumentException("file or filename object is null");
				}
				/**
				 * 判断图片是否允许的类型
				 */
				if(!FileUtil.isAllowUpImg(fileName)){
					throw new IllegalArgumentException("不被允许的上传文件类型");
				}
				/*
				生成文件的路径
				 */
				String ext = FileUtil.getFileExt(fileName);
				fileName = DateUtil.toString(new Date(), "mmss") + StringUtil.getRandStr(4) + "." + ext;
				String static_server_path= SystemSetting.getStatic_server_path();
				String filePath =  static_server_path + "/attachment/";
				if(subFolder!=null){
					filePath+=subFolder +"/";
				}
				Calendar now = Calendar.getInstance();
				int year=now.get(Calendar.YEAR);
				int month=now.get(Calendar.MONTH) + 1;
				int date=now.get(Calendar.DAY_OF_MONTH);
				int minute=now.get(Calendar.HOUR_OF_DAY);
				String timePath="";
				if(year!=0){
					timePath+=year+"/";;
				}
				if(month!=0){
					timePath+=month+"/";;
				}
				if(date!=0){
					timePath+=date+"/";;
				}
				if(minute!=0){
					timePath+=minute+"/";;
				}
				String path  = EopSetting.FILE_STORE_PREFIX+ "/attachment/" +(subFolder==null?"":subFolder)+"/"+timePath+"/"+fileName;
				filePath +=timePath;
				filePath += fileName;
				/**
				 * 写入文件  将文件写出
				 */
				FileUtils.copyInputStreamToFile(stream, new File(filePath));
			} else {
				System.out.println("不允许上传的文件格式,请上传gif,jpg,bmp,swf格式文件。");
			}
		}
	}

/**
	 * 是否是允许上传的图片格式
	 * @param imgFileName
	 * @return
	 */
	public static boolean isAllowUpImg(String imgFileName){
		imgFileName = imgFileName.toLowerCase();
		String allowTYpe = "gif,jpg,bmp,png,jpeg,swf,mp4";
		if (!imgFileName.trim().equals("") && imgFileName.length() > 0) {
			String ex = imgFileName.substring(imgFileName.lastIndexOf(".") + 1, imgFileName.length());
			return allowTYpe.toUpperCase().indexOf(ex.toUpperCase()) >= 0;
		} else {
			return false;
		}
	}
form表单就很简单
<form action="/core/admin/adv/add-savetest.do" method="post" enctype="multipart/form-data">
    <input type="file" label="文件上传" name="pic" accept="image/*,.swf">
    <button type="submit">提交</button>
</form>

在测试过程中遇到一个问题

org.springframework.web.multipart.MultipartException: The current request is not a multipart request

当时就是应为没有写 enctype='multipart/form-data'

参考链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值