victory的博客

长安一片月,万户捣衣声

0%

SpringMVC | 上传和下载文件

上传和下载文件

注意:上传文件需要在springMVC.xml中配置如下所示bean:

<!-- 
    处理文件,将客户端上传的File文件处理为MultipartFile
    注意:文件解析器bean中的id必须设置为multipartResolver 
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 设置文件解析的编码,注意一定要和页面的pageEncoding保持一致 -->
    <property name="defaultEncoding" value="UTF-8"></property>
    <!-- 设置最大上传文件大小 -->
    <property name="maxUploadSize" value="88888888"></property>
</bean>

file.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>Insert title here</title>
</head>
<body>
    <a href="down">下载图片</a>
    
    <form action="up" method="post" enctype="multipart/form-data">
        头像:<input type="file" name="uploadFile" />
        描述:<input type="text" name="desc" />
        <input type="submit" value="上传" />
    </form>
    
    <form action="up_old" method="post" enctype="multipart/form-data">
        头像:<input type="file" name="uploadFile" />
        描述:<input type="text" name="desc" />
        <input type="submit" value="上传" />
    </form>
</body>
</html>

TestUploadAndDownController.java

package com.atguigu.test;

import java.io.File;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import com.sun.org.apache.xalan.internal.xsltc.trax.OutputSettings;

@Controller
public class TestUploadAndDownController{
    @RequestMapping("/down")
    public ResponseEntity<byte[]> down(HttpSession session) throws IOException{
        //获取下载文件的路径
        String realPath = session.getServletContext().getRealPath("img");
        String finalPath = realPath + File.separator + "1.jpg";
        InputStream is = new FileInputStream(finalPath);
        //available():获取输入流所读取的文件的最大字节数
        byte[] b = new byte[is.available()];
        is.read(b);
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename=zzz.jpg");
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(b, headers, statusCode);
        return entity;
    }
    
    //第一种上传方式
    @RequestMapping(value="/up_old", method=RequestMethod.POST)
    public String up_old(String desc, MultipartFile uploadFile, HttpSession session) throws IOException{
        //String name = uploadFile.getName();
        //String originalFilename = uploadFile.getOriginalFilename();
        //System.out.println(name+","+originalFilename);
        
        //获取上传文件的名称
        String filename = uploadFile.getOriginalFilename();
        String path = session.getServletContext().getRealPath("photo") + File.separator + filename;
        
        //获取输入流
        InputStream is = uploadFile.getInputStream();
        
        //获取输出流
        File file = new File(path);
        OutputStream os = new FileOutputStream(file);
        
        //文件上传
//        int i = 0;
//        while((i = is.read()) != -1){
//            os.write(i);
//        }
        
        int i = 0;
        byte[] b = new byte[1024];
        while((i = is.read(b)) != -1){
            os.write(b, 0, i);
        }
        
        //关闭流
        os.close();
        is.close();
        return "success";
    }
    
    //第二种上传方式
    @RequestMapping(value="/up", method=RequestMethod.POST)
    public String up(String desc, MultipartFile uploadFile, HttpSession session) throws IOException{
        //获取上传文件的名称
        String fileName = uploadFile.getOriginalFilename();
        String finalFileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
        String path = session.getServletContext().getRealPath("photo") + File.separator + finalFileName;
        
        File file = new File(path);
        uploadFile.transferTo(file);
        return "success";
    }
}