用SpringMVC搭建文件上传和下载

来源:互联网 发布:php safe mode 编辑:程序博客网 时间:2024/05/18 10:15
----控制层代码
package com.lq.controller;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.URLEncoder;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;import com.lq.service.IUserService;/** * response.setHeader("content-disposition", "attachment;filename=a.txt"); * @author Administrator * */@Controllerpublic class UploadController {@Autowiredprivate IUserService userService;public IUserService getUserService() {return userService;}public void setUserService(IUserService userService) {this.userService = userService;}@RequestMapping("/upload.do")public ModelAndView doUpload(HttpServletRequest request,HttpServletResponse response){/** * 1.创建文件解析器工厂 * 2.实例化文件解析器 * 3.通过解析器去处理request请求  ,并返回  FileItem列表 * 4.处理FileIetm */DiskFileItemFactory factory  = new DiskFileItemFactory();ServletFileUpload upload = new ServletFileUpload(factory);InputStream in=null;FileOutputStream out=null;try {List<FileItem> list = upload.parseRequest(request);String filename="";for(int i=0;i<list.size();i++){FileItem fileitem = list.get(i);if(!fileitem.isFormField()){//上传的文件打开输入流,以便java代码读取其中的信息in= fileitem.getInputStream();//1.pngfilename = fileitem.getName();filename = filename.substring(filename.lastIndexOf("\\")+1);System.out.println(request.getSession().getServletContext().getRealPath("image"));String path = request.getSession().getServletContext().getRealPath("image");String filepath = path+"\\"+filename;out = new FileOutputStream(filepath);int j;byte[] b = new byte[512];     //600个字节  88   0 1 。。。88    89 while((j=in.read(b))!=-1){out.write(b,0,j);}userService.insertFilePath(filepath, filename);}}List flist = userService.queryAllFilePath();ModelAndView mv = new ModelAndView();//mv.addObject("image", "image\\"+filename);mv.addObject("flist", flist);mv.setViewName("/sucess.jsp");return mv;} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {in.close();out.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return null;} @RequestMapping("downLoad.do")public void downLoadFile(HttpServletRequest request,HttpServletResponse response){String filename = request.getParameter("filename");String path = request.getSession().getServletContext().getRealPath("image");String filepath = path+"\\"+filename;FileInputStream in=null;OutputStream out =null;try {in = new FileInputStream(filepath);byte[] b = new byte[512];int i;//设置能够下载的文件类型response.setContentType("multipart/form-data");//只有设置此属性才可以下载,否则文件将直接在浏览器显示  filename是下载文件时默认保存名称response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename, "utf-8"));out = response.getOutputStream();while((i=in.read(b))!=-1){out.write(b,0,i);}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {in.close();out.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}@RequestMapping("/doQueryFile.do")public ModelAndView doQueryFile(HttpServletRequest request,HttpServletResponse response){List flist = userService.queryAllFilePath();ModelAndView mv = new ModelAndView();//mv.addObject("image", "image\\"+filename);mv.addObject("flist", flist);mv.setViewName("/sucess.jsp");return mv;}}
----upload.JSP代码

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'upload.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>   <form action="upload.do" enctype="multipart/form-data" method="post">    <input type="file" name="file" multiple="multiple">    <input type="submit" value="上传">    </form>  </body></html>
--------success.jsp代码

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c"  %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'success.jsp' starting page</title>
    
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->


  </head>
  
  <body>
    <form action="doQueryFile.do" >
    文件名: <input type="text" name="filename"><input type="submit" value=" 查询">
   </form>  
   <c:forEach items="${flist}" var="f">
    <br><a href="downLoad.do?filename=${f.filename }">${f.filename }</a><br>
   </c:forEach>
  </body>
</html>

-------JSP页面


-------------项目框架


-----------------spring-servlet 配置文件


--------------引入包

------------


1 0
原创粉丝点击