前端上传

<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. 关于c语言变量的内存分布测试程序

    #include <stdio.h> #include <stdlib.h> ; // 常全局变量 ; // 初始化全局变量 int uninit_global; // 未初始 ...

  2. 安装node-sass

    SASS_BINARY_SITE=https://npm.taobao.org/mirrors/node-sass/ npm install node-sass

  3. Linux使用rsync客户端与服务端同步目录进行备份

    一.服务端设置 1. 修改 server 端配置 # vi /etc/rsyncd.conf 修改: uid = nobody # 该选项指定当该模块传输文件时守护进程应该具有的uid.默认值为&qu ...

  4. 第五十四节,socketserver通讯模块实现并发操作,真多线程并发

    socketserver通讯模块实现并发操作,基于select.epoll.socket.多线程,实现的正真多线程多并发 socketserver通讯模块底层调用的socket模块,只是它作了处理基于 ...

  5. json解析的函数eval_r() 和 JSON.parse()

              eval_r()解析的字符串格式是'({"data":"hello","num":"5"})'   ...

  6. 有关app的一些小知识

    META相关 1. 添加到主屏后的标题(IOS)<meta name="apple-mobile-web-app-title" content="标题"& ...

  7. 【Office Web Apps】在 SharePoint 中使用 Office Web Apps

    在 SharePoint 中使用 Office Web Apps 在安装并配置了 Microsoft Office Web Apps 的 SharePoint 网站上,通过 Office Web Ap ...

  8. SharePoint2013基于Form(FBA)的AD认证登陆

    来源于:http://www.haogongju.net/art/1964313 1. 使用SharePoint2013实现基于AD的Form认证,首先创建一个Web Application,步骤如下 ...

  9. 归并排序的go语言与C++实现对比

    最近对go语言发生了兴趣,发现go语言语法简洁,非常适合算法的描述和实现,于是对归并排序进行了实现. 例子中需要排序的队列是长度为100的从100到1的数列,排序算法是正序排序,排序正确的话,结果应当 ...

  10. 将MyEclipse中的项目导入到Eclipse中报错的解决放法

    1.导入项目后,会报红色感叹号, 将项目右键,点击红色框.