前端上传

<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, 上传文件消失的更多相关文章

  1. 更改Eclipse下Tomcat的部署目录 ,防止上传的文件是到eclipse的克隆的tomcat上的webapp,而不是tomcat本身的webapp

    使用eclipse开发是因为机器不够用myeclipse,eclipse也比myeclipse清爽很多,启动速度也快.这里的搭建开发环境使用: Jdk1.6+Tomcat6+Eclipse JEE, ...

  2. javaWeb中的文件上传下载

    在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...

  3. Day22 文件上传下载和javaMail

    day22总结 文件上传概述   1 文件上传的作用 例如网络硬盘!就是用来上传下载文件的. 在智联招聘上填写一个完整的简历还需要上传照片呢.   2 文件上传对页面的要求 上传文件的要求比较多,需要 ...

  4. php实现文件上传下载功能小结

    文件的上传与下载是项目中必不可少的模块,也是php最基础的模块之一,大多数php框架中都封装了关于上传和下载的功能,不过对于原生的上传下载还是需要了解一下的.基本思路是通过form表单post方式实现 ...

  5. JavaWeb实现文件上传下载功能实例解析

    转:http://www.cnblogs.com/xdp-gacl/p/4200090.html JavaWeb实现文件上传下载功能实例解析 在Web应用系统开发中,文件上传和下载功能是非常常用的功能 ...

  6. Java实现对文件的上传下载操作

    通过servlet,实现对文件的上传功能 1.首先创建一个上传UploadHandleServlet ,代码如下: package me.gacl.web.controller; import jav ...

  7. JavaWeb 文件 上传 下载

    文件上传下载对于一个网站来说,重要性不言而喻.今天来分享一个JavaWeb方式实现的文件上传下载的小例子. 项目依赖 项目目录 工作流程 文件上传 表单处的设置 服务器端 上传功能的实现 upload ...

  8. SpringMVC 文件上传下载

    目录 文件上传 MultipartFile对象 文件下载 上传下载示例 pom.xml增加 创建uploadForm.jsp 创建uploadForm2.jsp 创建userInfo.jsp spri ...

  9. java 实现文件上传下载以及查看

    项目的目录结构 代码  IOUtils.java package cn.edu.zyt.util; import java.io.IOException; import java.io.InputSt ...

随机推荐

  1. 《JS权威指南学习总结--6.5枚举属性》

    内容要点: 一.for/in循环 1.for/in循环可以在循环体中遍历对象中所有可枚举的属性(包括自有属性和继承的属性),把属性名称赋值给循环变量.对象继承的内置方法不可枚举,但在代码中给对象添加的 ...

  2. hdu_5877_Weak Pair(离散+DFS+树状数组)

    题目链接:hdu_5877_Weak Pair 题意: 给你一棵树,让你找有多少对满足那两个条件的weak pair 题解: 有人用Treap,我不会,然后我用树状数组+离散来替代Treap,用DFS ...

  3. openwrt 更改 debug 等级(hostapd)

    https://wiki.openwrt.org/doc/devel/debugging 调试hostapd,其中hostapd的调试等级如下: # Levels (minimum value for ...

  4. Hibernate配置文件的hbm2ddl.auto属性

    今天遇到一个有意思的问题,我目前做的一个网站采用Spring MVC + Spring + Hibernate的架构,我通过页面插入了一些数据到数据库,可是每次重启tomcat之后,数据都莫名其妙地丢 ...

  5. Zeppelin使用spark解释器

    Zeppelin为0.5.6 Zeppelin默认自带本地spark,可以不依赖任何集群,下载bin包,解压安装就可以使用. 使用其他的spark集群在yarn模式下. 配置: vi zeppelin ...

  6. 【转】ActiveMQ与虚拟通道

    郑重提示,本文转载自http://shift-alt-ctrl.iteye.com/blog/2065436 ActiveMQ提供了虚拟通道的特性(Virtual Destination),它允许一个 ...

  7. HUST 1358 Uiwurerirexb jeqvad(模拟解密)

    Uiwurerirexb jeqvad Description Fmur lan oxbrvu mzx, E abpxcay Jvmffabza qdxwfaou eb vmjsad.xdz, eb ...

  8. 判断括号字符串是否为合法+求n对括号的所有组合

    n对括号的有效组合数 参考:https://zh.wikipedia.org/wiki/%E5%8D%A1%E5%A1%94%E5%85%B0%E6%95%B0 import java.util.Ar ...

  9. ZOJ 3702 Gibonacci number

    本来已经关上电脑了 但还是想打开电脑纪念一下这充实的一天…… 第一节高数课讲新课级数 讲完一个知识点 想问问女票今天咋又没来上课…… 突然发现院长问我自费去不去省赛…… !!! 当然是去啊! ……虽然 ...

  10. hadoop---wordcount命令

    [zznu@master file]$ hadoop jar ~/hadoop-2.5.2/share/hadoop/mapreduce/hadoop-mapreduce-examples-2.5.2 ...