Spring MVC的文件上传下载

来源:互联网 发布:sql 2000 win7 64 编辑:程序博客网 时间:2024/05/16 01:57

 代码:

uploadForm.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>文件上传</title></head><body><h2>文件上传</h2><form action="upload" enctype="multipart/form-data" method="post"><table><tr><td>文件描述:</td><td><input type="text" name="description"></td></tr><tr><td>请选择文件:</td><td><input type="file" name="file"></td></tr><tr><td><input type="submit" value="上传"></td></tr></table></form></body></html>

success.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>测试文件上传</title></head><body>上传文件成功!</body></html>

error.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>测试文件上传</title></head><body>上传文件失败!</body></html>

registerForm.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>用户注册</title></head><body><h2>用户注册</h2><form action="register" enctype="multipart/form-data" method="post"><table><tr><td>用户名:</td><td><input type="text" name="username"></td></tr><tr><td>请上传头像:</td><td><input type="file" name="image"></td></tr><tr><td><input type="submit" value="注册"></td></tr></table></form></body></html>

userInfo.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>文件下载</title></head><body><h3>文件下载</h3><a href="download?filename=${requestScope.user.image.originalFilename}">${requestScope.user.image.originalFilename}</a></body></html>

User.java

package com.bean;import java.io.Serializable;import org.springframework.web.multipart.MultipartFile;public class User implements Serializable {private String username;private MultipartFile image;public User() {super();// TODO Auto-generated constructor stub}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public MultipartFile getImage() {return image;}public void setImage(MultipartFile image) {this.image = image;}}

FileUploadController.java

package com.control;import java.io.File;import javax.servlet.http.HttpServletRequest;import org.apache.commons.io.FileUtils;import com.bean.*;import org.springframework.http.HttpHeaders;import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.PathVariable;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.multipart.MultipartFile;@Controllerpublic class FileUploadController{@RequestMapping(value="/{formName}") public String loginForm(@PathVariable String formName){// 动态跳转页面return formName;} // 上传文件会自动绑定到MultipartFile中 @RequestMapping(value="/upload",method=RequestMethod.POST) public String upload(HttpServletRequest request,@RequestParam("description") String description,@RequestParam("file") MultipartFile file) throws Exception{     System.out.println(description);    // 如果文件不为空,写入上传路径if(!file.isEmpty()){// 上传文件路径String path = request.getServletContext().getRealPath("/images/");// 上传文件名String filename = file.getOriginalFilename();    File filepath = new File(path,filename);// 判断路径是否存在,如果不存在就创建一个        if (!filepath.getParentFile().exists()) {         filepath.getParentFile().mkdirs();        }        // 将上传文件保存到一个目标文件当中file.transferTo(new File(path+File.separator+ filename));return "success";}else{return "error";}  }  @RequestMapping(value="/register") public String register(HttpServletRequest request,@ModelAttribute User user,Model model)throws Exception{System.out.println(user.getUsername());// 如果文件不为空,写入上传路径if(!user.getImage().isEmpty()){// 上传文件路径String path = request.getServletContext().getRealPath("/images/");// 上传文件名String filename = user.getImage().getOriginalFilename();    File filepath = new File(path,filename);// 判断路径是否存在,如果不存在就创建一个        if (!filepath.getParentFile().exists()) {         filepath.getParentFile().mkdirs();        }        // 将上传文件保存到一个目标文件当中        user.getImage().transferTo(new File(path+File.separator+ filename));        model.addAttribute("user", user);        return "userInfo";}else{return "error";}}  @RequestMapping(value="/download") public ResponseEntity<byte[]> download(HttpServletRequest request, @RequestParam("filename") String filename, Model model)throws Exception{// 下载文件路径String path = request.getServletContext().getRealPath("/images/");File file = new File(path+File.separator+ filename);        HttpHeaders headers = new HttpHeaders();          // 下载显示的文件名,解决中文名称乱码问题          String downloadFielName = new String(filename.getBytes("UTF-8"),"iso-8859-1");        // 通知浏览器以attachment(下载方式)打开图片        headers.setContentDispositionFormData("attachment", downloadFielName);         // application/octet-stream : 二进制流数据(最常见的文件下载)。        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);   }}

截图:









0 0
原创粉丝点击