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()。