上传下载文件, 同时部署在webapps下, 而不是项目下,防止重新部署tomcat, 上传文件消失
前端上传
<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>";
上传下载文件, 同时部署在webapps下, 而不是项目下,防止重新部署tomcat, 上传文件消失的更多相关文章
- 更改Eclipse下Tomcat的部署目录 ,防止上传的文件是到eclipse的克隆的tomcat上的webapp,而不是tomcat本身的webapp
使用eclipse开发是因为机器不够用myeclipse,eclipse也比myeclipse清爽很多,启动速度也快.这里的搭建开发环境使用: Jdk1.6+Tomcat6+Eclipse JEE, ...
- javaWeb中的文件上传下载
在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...
- Day22 文件上传下载和javaMail
day22总结 文件上传概述 1 文件上传的作用 例如网络硬盘!就是用来上传下载文件的. 在智联招聘上填写一个完整的简历还需要上传照片呢. 2 文件上传对页面的要求 上传文件的要求比较多,需要 ...
- php实现文件上传下载功能小结
文件的上传与下载是项目中必不可少的模块,也是php最基础的模块之一,大多数php框架中都封装了关于上传和下载的功能,不过对于原生的上传下载还是需要了解一下的.基本思路是通过form表单post方式实现 ...
- JavaWeb实现文件上传下载功能实例解析
转:http://www.cnblogs.com/xdp-gacl/p/4200090.html JavaWeb实现文件上传下载功能实例解析 在Web应用系统开发中,文件上传和下载功能是非常常用的功能 ...
- Java实现对文件的上传下载操作
通过servlet,实现对文件的上传功能 1.首先创建一个上传UploadHandleServlet ,代码如下: package me.gacl.web.controller; import jav ...
- JavaWeb 文件 上传 下载
文件上传下载对于一个网站来说,重要性不言而喻.今天来分享一个JavaWeb方式实现的文件上传下载的小例子. 项目依赖 项目目录 工作流程 文件上传 表单处的设置 服务器端 上传功能的实现 upload ...
- SpringMVC 文件上传下载
目录 文件上传 MultipartFile对象 文件下载 上传下载示例 pom.xml增加 创建uploadForm.jsp 创建uploadForm2.jsp 创建userInfo.jsp spri ...
- java 实现文件上传下载以及查看
项目的目录结构 代码 IOUtils.java package cn.edu.zyt.util; import java.io.IOException; import java.io.InputSt ...
随机推荐
- JavaBean 反射机制实现自动配置数据
声明:该版本是没完成的.该博文只做记录代码用 String memberType(String name) throws Exception { return getType(getClass().g ...
- python 强制结束线程的坑
网上流传了两种能强制结束线程的错误姿势 第一种:通过setDaemon来结束线程 http://www.cnblogs.com/jefferybest/archive/2011/10/09/22040 ...
- 登录SQL注入
在登录页面的账号密码的输入框中分别输入,这个值:1' or '1'='1 一,验证的数据库语句,讲传人的值组合成数据库语句: public DataTable CheckLogin(string na ...
- java 用双向链表实现SJBLinkedList
public class SJBLinkedList{ private Node first; private Node last; private int size; public int size ...
- sql 多个字段排序,头一个字段排序完,再对第二个字段进行排序(以此类推)
现根据num排序,num数字相同的根据时间进行排序,都是降序DESC SELECT * FROM counts ORDER BY num DESC,create_time DESC
- hdu_5927_Auxiliary Set(xjb搞)
题目链接:hdu_5927_Auxiliary Set 题意: 给一棵n个节点的树,最开始全部都是重点,现在有q个询问,每次给你一些轻点,并叫你输出整棵树的重点数量, 轻点可能会变为重点,如果这个轻点 ...
- Cmake常用指令
1. cmake_minimum_required(VERSION 2.8) 检查cmake的版本,至少为2.8 2. project(helloworld) ...
- Delphi中,FALSE 和 nil ,true 和 nil,0的区别
True和False是布尔型(Boolean)的值,就是"是"或"否"的意思.nil就是空,一般用于指针或对象变量,指对针或对象对象一般初始化为nil或者释放后 ...
- 推荐学习c语言的几个开源项目
1. Webbench Webbench是一个在linux下使用的非常简单的网站压测工具.它使用fork()模拟多个客户端同时访问我们设定的URL,测试网站在压力下工作的性能,最多可以模拟3万个并发连 ...
- SecureCRT - 使用方法和技巧
1. 保活防掉线选项 -> 会话选项 -> 终端勾选 自动重新连接, 发送协议 NO-OP 每60秒 2. 拷贝与粘贴的设置选项 -> Global options -> Te ...