用SpringMVC搭建文件上传和下载

本文介绍了一个使用Java Servlet和Spring框架实现的文件上传和下载功能。该应用包括了控制层代码,用于处理文件上传请求并将文件存储到服务器指定路径,同时提供文件下载功能。通过解析HTTP请求,将上传的文件信息保存到数据库,并且可以查询所有已上传的文件列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

----控制层代码
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
 *
 */
@Controller
public class UploadController {
	@Autowired
	private 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.png
					filename = 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 block
			e.printStackTrace();
		}finally{
			try {
				in.close();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.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 block
			e.printStackTrace();
		}finally{
			try {
				in.close();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.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 配置文件

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

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值