多文件可编辑上传
<form action="../reportset/add.action" name="queryForm" enctype="multipart/form-data" method="post" >
<input type="button" οnclick="addFileInput()" value="添加文件行"></input>
<table>
<thead>
<tr style="background-color:#EFEFEF">
<th width="30%" colspan="1" nowrap="true" rowspan="1"><strong>待上传文件名</strong></th>
<th width="20%" colspan="1" rowspan="1"><strong>开放下载</strong></th>
<th width="20%" colspan="1" rowspan="1"><strong>删除</strong></th>
</tr>
</thead>
<tbody class="filecontent" id="filecontent">
<tr>
<td><input type="file" name="file" accept="*.jpg,*.png,*.gif,*.pdf,*.doc,*.docx,*.xls,*.xlsx,*.tar.gz,*.zip,*.rar"></td>
<td><input type="checkbox" name="downloads" fileid="1" οnclick="setUpfileValue(this)" value="0"/>
<input type="hidden" id="1upfile" name="downloads" value="0"/></td>
<td><a οnclick="deleteTr(this)">删除</a></td>
</tr>
</tbody>
</table>
<input type="hidden" id="upfileId" name="upfileId" value="1"/>
</form>
js
function addFileInput(){
var upfileId = $('input[name="upfileId"]').val();
$('input[name="upfileId"]').val(upfileId+1);
var html = '';
html += "<tr>" +
"<td><input type='file' name='file' accept=''></td>"+
"<td><input type=\"checkbox\" name=\"downloads\" fileid=\""+upfileId+"\" οnclick=\"setUpfileValue(this)\" value=\"0\"/>\n" +
"<input type=\"hidden\" id=\""+upfileId+"upfile\" name=\"downloads\" value=\"0\"/></td>" +
"<td><a οnclick=\"deleteTr(this)\">删除</a></td>" +
"</tr>";
$('.filecontent').append(html);
}
function deleteTr(obj){
$(obj).parent().parent().remove();
}
function setUpfileValue(obj){
var fileid = $(obj).attr('fileid');
var className= fileid+'upfile';
document.getElementById(className).value =obj.checked?1:0;
}
@RequestMapping(value="/reportset/add.action")
public String add(ReportsetDto dto, @RequestParam("file") List<CommonsMultipartFile> files, Integer[] downloads,String organid ){
for(int i=0 ;i<files.size();i++){
reportsetService.saveFile(dto,files.get(i),downloads[i]);
}
return "reportset/reportset-reload";
}
public boolean saveFile(ReportsetDto dto, CommonsMultipartFile file, Integer download){
if(file == null) {
return false;
}
// 先创建保存文件的文件夹
File reportsetPath = new File("/Users/mazhen/desktop/reportpath/"+dto.getId());
// 判断文件夹已经存在
if(!reportsetPath.exists()){
boolean mkdir = reportsetPath.mkdir();
logger.info("路径不存在!"+reportsetPath.getAbsolutePath() + (mkdir==true?"成功":"失败"));
}
String fileNameWithPath = file.getFileItem().getName();
String fileName = fileNameWithPath.substring(fileNameWithPath.lastIndexOf(File.separator)+1);
File newFile=new File(this.getStorepath(dto.getId(), fileName));
// 创建文件
if(!newFile.exists()&&!newFile.isDirectory()){
boolean mkdir = newFile.mkdir();
logger.info("文件不存在!"+newFile.getAbsolutePath() + (mkdir==true?"成功":"失败"));
}
//通过CommonsMultipartFile的方法直接写文件
try {
// 文件上传
file.transferTo(newFile);
} catch (IOException e) {
logger.error("文件上传失败",e);
// TODO 失败处理
return false;
}
return true;
}