上传下载文件, 同时部署在webapps下, 而不是项目下,防止重新部署tomcat, 上传文件消失
2024-10-14 11:11:02
前端上传
<a href='javascript:upload("+data[i].id+")' title='Upload Report'> <img src='${pageContext.request.contextPath}/FlatUI/img/edit2.png' width=18px height=18px/></a>
js函数
function upload(id){
var winObj = window.open ("/portal/trip/toUpload?id="+id, "newwindow", "height=700, width=800, toolbar =no, menubar=no, scrollbars=no, resizable=no, location=no, status=no, top=50,left=1100");
var loop = setInterval(function() {
if(winObj.closed) {
clearInterval(loop);
window.location.reload();
}
}, 1);
}
controller
@RequestMapping("/toUpload")
public String toUpload(Long id, HttpServletRequest request){
request.setAttribute("id",id);
return "/tripController/toUpload";
}
前台toUpload.jsp
<form name="fileForm" action="/portal/trip/upload" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" id="id" value="${id }">
<font size="2" face="Arial" color="#004779">Select: </font> <input type="file" name="file" style="color:#95a5a6; padding-left:5px;border-radius:5px; width:500px; height:28px; vertical-align:middle;">
<input type="submit" value="Upload" style="color:#2c3e50;font-size:12px; font-weight:bold; border-radius:5px; vertical-align:middle;height:30px; width:60px; "> </form>
controller upload函数
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(@RequestParam("file") MultipartFile image, Long id,HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException{
// 转型为MultipartHttpRequest
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// 根据前台的name名称得到上传的文件
MultipartFile file = multipartRequest.getFile("file");
// 获得文件名:
String realFileName = file.getOriginalFilename();
// 获取路径
String ctxPath = request.getSession().getServletContext().getRealPath("/").substring(0, request.getSession().getServletContext().getRealPath("/").lastIndexOf(request.getContextPath().replace("/", ""))); File dirPath = new File(ctxPath+File.separator+"upload"+File.separator+"trip"+File.separator);
System.out.println("路径" + dirPath);
/*String ctxPath = request.getSession().getServletContext()
.getRealPath("/download/trip/")
+ "/" ;
System.out.println("路径" + ctxPath);
// 创建文件
File dirPath = new File(ctxPath); */
if (!dirPath.exists()) {
dirPath.mkdir();
}
else{
System.out.println("文件夹已经存在");
}
File uploadFile = new File(dirPath +File.separator+ realFileName);
FileCopyUtils.copy(file.getBytes(), uploadFile);
request.setAttribute("files", loadFiles(request)); tripService.updateById(id,"filename",realFileName);
tripService.updateById(id,"ip",request.getRemoteHost());
request.setAttribute("ip", request.getRemoteHost());
//List<String> a = loadFiles(request);
return "/tripController/success";
}
public List<String> loadFiles(HttpServletRequest request) {
List<String> files = new ArrayList<String>();
String ctxPath = request.getSession().getServletContext().getRealPath("/").substring(0, request.getSession().getServletContext().getRealPath("/").lastIndexOf(request.getContextPath().replace("/", ""))); File file = new File(ctxPath+File.separator+"upload"+File.separator+"trip"+File.separator);
if (file.exists()) {
File[] fs = file.listFiles();
String fname = null;
for (File f : fs) {
if (f.isFile()) {
fname=f.getName();
files.add(fname);
}
}
}
return files;
}
@RequestMapping("/download/{fileName:.*}")
public void download(@PathVariable("fileName") String fileName,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
response.setContentType("text/html;charset=utf-8");
java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
String ctxPath = request.getSession().getServletContext().getRealPath("/").substring(0, request.getSession().getServletContext().getRealPath("/").lastIndexOf(request.getContextPath().replace("/", "")))+File.separator+"upload"+File.separator+"trip"+File.separator;
String downLoadPath = ctxPath + fileName;
System.out.println(downLoadPath);
try {
long fileLength = new File(downLoadPath).length();
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment; filename="
+java.net.URLEncoder.encode(fileName, "UTF-8").replace("+","%20"));
// + new String(fileName.getBytes("ISO8859-1"), "utf-8"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
}
success.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript" src="../js/jquery-1.4.2.min.js"></script>
<title></title>
</head>
<body>
<font size="4" face="Arial" color="#004779"><strong>Upload Success!</strong></font>
<hr>
<font size="2" face="Arial" color="#004779"><strong>File List:</strong>
<c:forEach var="month" items="${files}">
<li><a href="/portal/trip/download/${month}">${month}</a> </li>
</c:forEach>
</font>
<hr><br>
<%-- <a href="${pageContext.request.contextPath}/index.jsp">返回</a> --%>
</body>
</html>
下载
if(data[i].filename==null)
str+="<td align='center' bordercolor='#DEDEDE'></td>";
else
str+="<td align='center' bordercolor='#DEDEDE'><a href='/portal/trip/download/"+data[i].filename+"' title='Business Trip Materials Download'><img src='${pageContext.request.contextPath}/FlatUI/img/link.png' width=15px height=15px/></a></td>";
最新文章
- Servlet监听器笔记总结
- sql server left 和right 函数
- arcgis软件集合
- 如何让ie 7 支持box-shadow
- C# 向Http服务器送出 POST 请求
- Collecting Bugs(POJ 2096)
- 在mac系统上安装Eclipse,编写java程序
- RequireJS入门(二) 转
- 局部化原理(Laplace渐进估计方法)
- c语言向文件中写入
- linux编辑器 vi的使用
- javascript和jquery动态创建html元素
- 插件式Web框架
- DOM-based XSS Test Cases
- LeetCode编程训练 - 折半查找(Binary Search)
- 题解-PKUWC2018 随机游走
- 【Java】将字节转换成十六进制、BCD码输出
- Linux regulator系统
- wpf 查找 子元素
- assert用法总结
热门文章
- openstack私有云布署实践【13.2 网络Neutron-compute节点配置(办公网环境)】
- [妙味JS基础]第十课:日期对象、时钟倒计时
- 一起看看2016中国第三届CSS开发者大会有哪些大咖演讲
- magento数据添加
- powder designer 转数据库
- hdu_5831_Rikka with Parenthesis II(模拟)
- NOIP2010-普及组复赛模拟试题-第二题-数字积木
- 菲菲更名宝贝(批量更名软件) v8.0 绿色版
- eclipse设置java虚拟机内存大小
- 2.按要求编写Java应用程序: (1)编写西游记人物类(XiYouJiRenWu) 其中属性有:身高(height),名字(name),武器(weapon) 方法有:显示名字(printName),显示武器(printWeapon) (2)在主类的main方法中创建二个对象:zhuBaJie,sunWuKong。并分别为他 们的两个属性(name,weapon)赋值,最后分别调用printNam