SpringMVC 文件上传及下载

首先需要导入jar包

创建一个jsp页面

package cn.happy.Controller;

import java.io.File;


import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class MyController {
    @RequestMapping(value="/first.do")
    public String doFirst(HttpSession session,MultipartFile uploadfile ) throws Exception{
        if (uploadfile.getSize()>0) {
            //获取前半部分路径
            String leftpath=session.getServletContext().getRealPath("/images");
            //获取文件名称
            String filename = uploadfile.getOriginalFilename();
            //限制文件类型
            if(filename.endsWith(".jpg")||filename.endsWith(".JPG")){
                    File file=new File(leftpath,filename);
                    uploadfile.transferTo(file);
        
            
            return "WELCOME.jsp";
        }
        }
        
        return "error.jsp";
    }

配置文件:

 <!-- 配置包扫描器-->
       <context:component-scan base-package="cn.happy.Controller"></context:component-scan>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>


<mvc:annotation-driven/>

多文件上传类似于单文件上传 区别在于:

 文件下载:

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
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.web.bind.annotation.RequestMapping;
@Controller
public class DownFile {
    @RequestMapping(value="/download.do")
     public ResponseEntity<byte[]> download() throws IOException {    
         //图片真实路径
            File file=new File("D:\brotherC.jpg");  
            HttpHeaders headers = new HttpHeaders();    
            String fileName=new String("brotherC.jpg".getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题  
            headers.setContentDispositionFormData("attachment", fileName);   
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);   
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);    
        }    
    }  
    
原文地址:https://www.cnblogs.com/Smile-123/p/6269675.html