SSH框架中批量上传文件|MultipartFile批量上传图片|Java中批量上传图片记录|玉念聿辉|大丑村吴明辉

HTML代码

	//设置multiple,允许上传多张
	<input type="file" name="roomImgIdFile" id="roomImgIdFile" class="default" onchange="liGeShi(this)" multiple>
	
	//方法liGeShi()用于判断文件格式
	function liGeShi(en) {
		var f = en.value;
		var hz = f.substring(f.length - 3);
		if (hz != 'png' && hz != 'PNG' && hz != 'jpg' && hz != 'JPG') {
			alert("请选择png或者jpg格式的文件");
			en.value = "";
		}
	}

Java代码

       在你的Controller类中进行接收和处理表单信息,下面只说MultipartFile接收文件的方法。

	//单张接收
	MultipartFile imgIdFile = request.getFile("roomImgIdFile");
	addFile("保存路径",imgIdFile );

	//上传多张图片时,接收如下
	List<MultipartFile> attachs = request.getFiles("roomImgIdFile");
	for (int i = 0; i < attachs.size(); i++) {
		addFile("保存路径",attachs.get(i));
	}

保存到本地代码

	//保存到本地的过度方法,一般做一些数据库操作之类的动作
	public String addFile(String dir, MultipartFile file) throws Exception {
		if (file == null || file.getOriginalFilename() == null || file.getOriginalFilename().equals("")) {
			return null;
		}
		if (file != null && file.getSize() > 0) {
			byte bytes[] = file.getBytes();
			String path = FileUtils.writeBytesToFile(dir,file.getOriginalFilename(), bytes);
			return path ;
		}
		return null;
	}

	//将数据流写入文件中
	public static String writeBytesToFile(String dir, String fileName, byte[] bytes) throws Exception {
		String path = dir + "自己保存路径的处理";
		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}
		if (fileName == null) {
			path = path + "可以做一些路径加密等" ;
		} else {
				path = path + "根据fileName来做一些路径加密等" ;
		}
		file = new File(path);
		if (!file.exists()) {
			file.createNewFile();
		}
		if (file != null && file.exists()) {
			FileOutputStream out = new FileOutputStream(file);
			out.write(bytes, 0, bytes.length);
			out.flush();
			out.close();
			return path;
		} else {
			return null;
		}
	}

总结

       比较简单,在你的input 中加入multiple即可支持多选上传,至于接收直接用MultipartFile 就可以了,多选和单选的区别主要是request.getFile()和request.getFiles()。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

玉念聿辉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值