Spring 实现文件上传与下载

文件上传

upload.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 <%@ include file="/taglibs.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

   <h2 >
   文件上传
  </h2> 
  
  <div class="pageContent">
  <form method="post" action="/dhcss/ssp/upload/upload.do" enctype="multipart/form-data">
      
      
      	<div class="pageFormContent nowrap" layoutH="97">
      	<input type="hidden" name="name" />
                 <input type="file" name="file"/>
			<div class="divider"></div>
			<p>自定义扩展请参照:dwz.validate.method.js</p>
			<p>错误提示信息国际化请参照:dwz.regional.zh.js</p>
		</div>
		<div class="formBar">
			<ul>
				<li><div class="buttonActive">
						<div class="buttonContent">
							<button type="submit">提交</button>
						</div>
					</div></li>
				<li><div class="button">
						<div class="buttonContent">
							<button type="button" class="close">取消</button>
						</div>
					</div></li>
			</ul>
		</div>
  
  </form>
  </div>

</body>
</html>

java 上传代码;

package com.dhcc.dhcss.ssp.sm;

import java.io.File;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

	@Controller //声明该类为控制器类
	@RequestMapping("/ssp/upload")
	public class FileUploadController implements ServletContextAware{ //实现ServletContextAware接口,获取本地路径

	 private ServletContext servletContext;

	 public void setServletContext(ServletContext servletContext) { //实现接口中的setServletContext方法
	  this.servletContext = servletContext;
	 }

	 @RequestMapping(value = "/upload", method = RequestMethod.POST) //将文件上传请求映射到该方法
	 public String handleFormUpload(@RequestParam("name") String name, //设置请求参数的名称和类型
	   @RequestParam("file") CommonsMultipartFile mFile,HttpServletRequest req) { //请求参数一定要与form中的参数名对应
	  if (!mFile.isEmpty()) {
	   //String path = this.servletContext.getRealPath("/");  //获取本地存储路径
		//  String path="/home/chen/";
		  String pc=req.getServletContext().getRealPath("/WEB-INF/conf.properties");
		  Configuration rc = new Configuration(pc);//相对路径
		  String path=rc.getValue("path");
	    System.out.println(path);
	    
	   //File file = new File(path + new Date().getTime() + ".jpg"); //新建一个文件
	   File file = new File(path + new Date().getTime()); //新建一个文件
	   System.out.println(file.getAbsolutePath());
	   try {
	    mFile.getFileItem().write(file); //将上传的文件写入新建的文件中
	   } catch (Exception e) {
	    e.printStackTrace();
	   }
	   
	   return "ssp/sm/uploadSuccess"; //返回成功视图
	  }else {
	   return "ssp/sm/uploadFail"; //返回失败视图
	  }
	 }

	public void setServletContext1(ServletContext arg0) {
		// TODO Auto-generated method stub
		
	}
	}

uploadSuccess.jsp:



<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3 align='center'><font color='red'>上传成功,请去主文件夹下查看~~</font></h3>
<a href="http://localhost:8080/dhcss">返回首页</a>
</body>
</html>





uploadFail.jsp: 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3 align='center'><font color='red'>上传失败~~</font></h3>
<a href="http://localhost:8080/dhcss">返回首页</a>
</body>
</html>


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

download.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="../../js/jquery-1.7.1.js"></script>
<title>upload</title>
</head>
<body>
<h2 >
   文件下载
  </h2> 
  <div>
  	<div class="pageFormContent nowrap" layoutH="97">
	请输入文件夹下要下载的文件名(限英文名)
	<input id='fileName' type="text" name="fileName" />
	
		<div class="divider"></div>
			<p>自定义扩展请参照:dwz.validate.method.js</p>
			<p>错误提示信息国际化请参照:dwz.regional.zh.js</p>
		</div>
		
		<div class="formBar">
			<ul>
				<li><div class="buttonActive">
						<div class="buttonContent">
							<a id="btn" href="/dhcss/download.do" target="blank"><button>下载</button></a>
						</div>
					</div></li>
				<li><div class="button">
						<div class="buttonContent">
							<button type="button" class="close">取消</button>
						</div>
					</div></li>
			</ul>
		</div>
		
	</div>
</body>
<script type="text/javascript">
$(function(){  
    $('a').click(function(){  
        var link=this.href+'?'+'fileName='+$('#fileName').val();  
        window.open(link);  
        return false;  
    });  
});  
</script>
</html>

java 文件下载代码:


package com.dhcc.dhcss.ssp.sm;

import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStream;  
  
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;  
  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestParam;
  
@Controller  
public class FileDownloadController {  
  
	//static final String dir = "/home/chen/";
	
	
    @RequestMapping("download.do")  
    public void downloadFile(@RequestParam String fileName,HttpServletResponse response,HttpServletRequest req){  
        response.setCharacterEncoding("utf-8");  
        response.setContentType("multipart/form-data");  
  
        response.setHeader("Content-Disposition", "attachment;fileName="+fileName);  
        String pc=req.getServletContext().getRealPath("/WEB-INF/conf.properties");
		  Configuration rc = new Configuration(pc);//相对路径
		  String dir=rc.getValue("path");
        try {  
            File file=new File(dir+fileName);  
            System.out.println(file.getAbsolutePath());  
            InputStream inputStream=new FileInputStream(file);  
            OutputStream os=response.getOutputStream();  
            byte[] b=new byte[1024];  
            int length;  
            while((length=inputStream.read(b))>0){  
                os.write(b,0,length);  
            }  
            inputStream.close();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}  



评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值