上传下载
程序员文章站
2022-07-13 12:46:55
...
循环添加/删除上传文件
没有限制格式
<script>
var i = 1;
$(document).ready(function(){
$("#btn_add1").click(function(){ //添加
var temp = '<div id="file_'+i+'"><input name="newFileName_'+i+'" type="file" /><input type="button" value="删除" onclick="del_1('+i+')"/></div>';
$(temp).appendTo($("#newFileNameAdd"));
i = i + 1;
});
});
//删除的方法
function del_1(o){
document.getElementById("newUploadAdd").removeChild(document.getElementById("file_"+o));
}
</script>
<form id="" enctype="multipart/form-data" method="post">
<tr>
<td align="center" style="background-color: #E7F3FB; vertical-align: middle;" width="20%" height="100px">
<font size="3">上传文件</font>
</td>
<td align="left" style="vertical-align: middle;">
<div id="newFileNameAdd">
<input type="file" name="newFileName" />
</div>
<input type="button" id="btn_add1" value="增加一行" >
</td>
</tr>
业务逻辑
public List<Map<String, Object>> upload(HttpServletRequest request, String orderId) throws Exception {
//入参String orderId,作为文件名。可不要该入参,也可添加其他入参
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date today = new Date();
String nowday = sdf.format(today);
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
Map<String, Object> res=new HashMap<String, Object>();
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap =mRequest.getFileMap();
//getRealPath("/")指代项目根目录,所以代码返回的是项目在容器中的实际发布运行的根路径
// private static final String UPLOADDIR = "uploadUserDir/";
String uploadDir = request.getSession().getServletContext().getRealPath("/")
+ FileOperateUtil.UPLOADDIR
+ nowday + "/"; //D:\Work\项目名\src\main\webappuploadUserDir/日期/
File file = new File(uploadDir); //D:\Work\项目名\src\main\webappuploadUserDir\日期
if (!file.exists()) {//不存在时候,创建文件或者文件夹
file.mkdirs(); // 注意与file.mkdir()的区别
}
Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator();//迭代器
while (it.hasNext()) {
Map.Entry<String, MultipartFile> entry = it.next();
MultipartFile mFile = entry.getValue();
//取得上传文件
String lFileName = "";
String path = "";
if(mFile != null){
String myFileName = mFile.getOriginalFilename();//取得当前上传文件的文件名称
//如果名称不为"",说明该文件存在,否则说明该文件不存在
if(myFileName.trim() !=""){
lFileName = orderId + "-" + mFile.getOriginalFilename();//重命名上传后的文件名
path = uploadDir + lFileName; //定义上传路径
File localFile = new File(path);
if (localFile.exists()){
logger.error("文件地址:" + path + "已存在内容!");
continue;
}
Long preTime = System.currentTimeMillis(); //记录上传过程起始时间
try {
mFile.transferTo(localFile);//上传
} catch (Exception e) {
e.printStackTrace();
res.put("err", "异常信息"+e.getMessage());
result.add(res);
return result;
}
Long finalTime = System.currentTimeMillis();
System.out.println(finalTime - preTime);//记录上传文件的时间
}
}
String fileName = mFile.getOriginalFilename();
//将路径保存到数据库中,以备下载
TrFillRefInfo ffInfo = new TrFillRefInfo();
ffInfo.setFileId(fInfoDao.getTableKey("TRFILLREFINFO"));
ffInfo.setOpSq(opSq);
ffInfo.setTktNo(tktNo);
ffInfo.setUploadFileName(fileName);
ffInfo.setSavePath(path);
try {
fInfoDao.save(ffInfo);
} catch (Exception e) {
e.printStackTrace();
}
}
res.put("suc", "sucess");
result.add(res);
return result;
}
mkdir()创建此抽象路径名称指定的目录(及只能创建一级的目录,且需要存在父目录)
mkdirs()创建此抽象路径指定的目录,包括所有必须但不存在的父目录。(及可以创建多级目录,无论是否存在父目录)
上传成功后文件路径及文件名
下载
<td align="center" id="orderId">${fillRefundDto.orderId}(controller层返回的对象)</td>
<tr>
<td align="center" style="background-color: #E7F3FB; vertical-align: middle;" width="20%" >
<font >已上传文件列表:</font>
</td>
<td>
<select id="upDownFile">
<c:forEach items="${refInfoVO}" var="re">
<option value="${re.uploadFileName}">${re.uploadFileName}</option>
</c:forEach>
</select>
<input type="button" value="下载" style="font:size=3;" onclick="download()"/>
</td>
</tr>
对应js方法
function download() {
//var postData={};
//postData["orderId"]=$("#orderId").text();//需要的参数
//postData["uploadFileName"]= $("#upDownFile option:selected").text();
window.open('${pageContext.request.contextPath}/*Controller/download?orderId='
+$("#orderId").text()
+ '&uploadFileName='
+ $("#upDownFile option:selected").text());
}
controller层对应方法
@RequestMapping("/download")
public void downloadFile(HttpServletRequest request,HttpServletResponse response) {
String orderId = request.getParameter("orderId");
String uploadFileName = request.getParameter("uploadFileName");
//根据入参查询数据库,得到其余字段信息
TrFillRefInfo fInfo = fillRefundService.getDownloadFile(orderId,uploadFileName);
try {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
String downLoadPath = fInfo.getSavePath();//得到文件保存的路径
File file = new File(downLoadPath);
//file =D:\Work\项目名\src\main\webappuploadUserDir\2017-11-08\B10063-1.png
String filename = fInfo.getUploadFileName();
//filename =1.png(文件名)
InputStream fis;
fis = new BufferedInputStream(new FileInputStream(downLoadPath));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
// 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
response.addHeader("Content-Disposition", "attachment;filename="
+ new String(filename.replaceAll(" ", "").getBytes("utf-8"),
"iso8859-1"));
response.addHeader("Content-Length", "" + file.length());
OutputStream os = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
os.write(buffer);// 输出文件
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
上一篇: 2019-04-30遍历