1.首先创建一个用来测试的jsp文件上传下载的页面 代码如下
<%@ page language=“java” contentType=“text/html; charset=UTF-8”
pageEncoding=“UTF-8”%>
2.在自己已经构建好的maven web项目中 pom.xml配置文件中添加上传下载所需要的jar包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
3.在spring的applicationContext.xml配置文件中添加文件上传解析器
4.在controller层实现上传下载的代码package com.chao.controller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
/**
- 下载 测试
- @author 王一土
*/
@Controller
@RequestMapping(“file”)
public class UoloadController {
@RequestMapping(value="/upload",method=RequestMethod.POST)
@ResponseBody
public String upload(MultipartFile file,HttpServletRequest request) throws IOException{
String path = request.getSession().getServletContext().getRealPath("upload");
String fileName = file.getOriginalFilename();
File dir = new File(path,fileName);
if(!dir.exists()){
dir.mkdirs();
}
file.transferTo(dir);
return fileName;
}
@RequestMapping("/down")
public void down(HttpServletRequest request,HttpServletResponse response) throws Exception{
String fileName = request.getSession().getServletContext().getRealPath("upload")+"/101.jpg";
InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
String filename = "下载文件.jpg";
filename = URLEncoder.encode(filename,"UTF-8");
response.addHeader("Content-Disposition", "attachment;filename=" + filename);
response.setContentType("multipart/form-data");
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
int len = 0;
while((len = bis.read()) != -1){
out.write(len);
out.flush();
}
out.close();
}