SpringMVC文件上传下载

不多说,代码:


Spring-config.xml
<!-- spring可以自动去扫描base-pack下面的包或者子包下面的java文件, 如果扫描到有Spring的相关注解的类,则把这些类注册为Spring的bean --> <context:component-scan base-package="org.fkit.controller"></context:component-scan> <!-- 视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/content/"/> <property name="suffix" value=".jsp"/> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 上传文件的上限(字节) --> <property name="maxUploadSize" value="10485760"/> <!-- 请求编码格式 --> <property name="defaultEncoding" value="UTF-8"></property> </bean>


package
org.fkit.domain; 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; } }
package org.fkit.controller;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.fkit.domain.User;
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;

@Controller
public class FileUploadController{
    @RequestMapping(value="/{forName}")
    public String ForName(@PathVariable String forName){
        //动态跳转页面
        return forName;
    }
    @RequestMapping(value="/register")
    public String register(HttpServletRequest request,@ModelAttribute User user,Model model)
            throws IllegalStateException, IOException{
        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
            model.addAttribute("user",user);
            return "userInfo";
        }else{
            return "errors";
        }
    }
 @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 downloadFileName=new String(filename.getBytes("UTF-8"),"iso-8859-1"); //通知浏览器以attachment(下载方式)打开图片 headers.setContentDispositionFormData("attachment", downloadFileName); //application/octet-streama:二进制流数据(最常见的的文件下载) headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED); } }
<%@ 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>

<%@ 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>

 

springMVC上传下载相当简单,非常适用

posted @ 2017-04-15 11:50  LuoBaiLin  阅读(381)  评论(0编辑  收藏  举报