import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.servlet.ModelAndView;
@Controller
@Scope("prototype")
@RequestMapping(value="/file")
public class FileController {
//文件上传方法
@RequestMapping(value="/upload.do")
public ModelAndView upload(@RequestParam(value="file") MultipartFile file,HttpServletRequest req){
//获取上传文件的目录和名称 upfile 为自行在根目录下创建的文件夹
String path = req.getSession().getServletContext().getRealPath("/")+"upfile/"+file.getOriginalFilename();
//创建目标文件
File targetFile = new File(path);
//保存
try {
file.transferTo(targetFile);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return new ModelAndView("admin/success.jsp");
}
//多文件上传方法
@RequestMapping(value="/uploadFiles.do")
public ModelAndView uploadFiles(HttpServletRequest req){
//获取请求中的N个文件
MultipartHttpServletRequest mhsreq = (MultipartHttpServletRequest)req;
//获取文件名
Iterator<String> iter = mhsreq.getFileNames();
//遍历取出
while(iter.hasNext()){
MultipartFile file = mhsreq.getFile(iter.next());
//判断...文件类型/文件大小...
//获取上传文件的目录和名称
String path = req.getSession().getServletContext().getRealPath("/")+"upfile/"+file.getOriginalFilename();
//创建目标文件
File targetFile = new File(path);
//保存
try {
file.transferTo(targetFile);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return new ModelAndView("showUser");
}
//下载
@RequestMapping(value="/download.do")
public ModelAndView download(String fileName,HttpServletRequest req,HttpServletResponse res) throws Exception{
//处理乱码问题
fileName = new String(fileName.getBytes("ISO-8859-1"),"utf-8");
//设置下载文件的内容响应
res.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName,"utf-8"));
//获取文件路径
String path = req.getSession().getServletContext().getRealPath("/")+"upfile/"+fileName;
//获得输入流
FileInputStream is = new FileInputStream(new File(path));
//输出流
OutputStream os = res.getOutputStream();
//读写操作
int length = 0;
byte[] bt = new byte[1024];
while((length=is.read(bt))>0){
os.write(bt,0,length);
}
os.close();
is.close();
return new ModelAndView("admin/success");
}
}
SpringMVC的文件上传下载
最新推荐文章于 2024-08-09 21:55:43 发布