文件的上传下载

时间:2021-06-23 20:58:43

文件上传下载

准备工作

Spring Web MVC也是使用Apache的common-fileupload,因此要在lib里面添加如下的jar包:

commons-fileupload-1.2.2.jar、commons-io-2.4.jar

 

为了处理中文文件名称的上传下载,把前面HelloWorld讲过的filter配置上

在Spring的配置文件中,配置处理文件上传的bean,如下:

<bean id= "multipartResolver" class= "org.springframework.web.multipart.commons.CommonsMultipartResolver ">

        <property name= "maxUploadSize" value= "104857600"/>

    </bean>

配置上就好了,Spring会自动找的

文件上传

文件上传示例,先看Controller部分,这里只是一个最基本的演示:

@Controller

@RequestMapping(value = "/fileope")

public class FileUploadController {

@RequestMapping(value = "upload", method = RequestMethod.POST)

  public String upload(           

          HttpServletRequest request, @RequestParam(value = "myFile", required = false) MultipartFile[] files) {

          try {

          for(int i=0;i<files.length;i++){

          FileUploadUtils.upload(request, files[i]);

          }

 

} catch (Exception e) {

e.printStackTrace();

}

          return "success";

  }

}

 

对应使用的FileUploadUtils:

public class FileUploadUtils {

    //默认大小 50M

    public static final long DEFAULT_MAX_SIZE = 52428800;

    //默认上传的地址

    public static  String defaultBaseDir = "upload";

 

    public static final String upload(HttpServletRequest request, MultipartFile file)throws Exception{

        String filename = extractFilename(file, defaultBaseDir);

        File desc = getAbsoluteFile(extractUploadDir(request), filename);

        file.transferTo(desc);

        return filename;

    }

    private static final File getAbsoluteFile(String uploadDir, String filename) throws IOException {

        if(uploadDir.endsWith("/")) {

            uploadDir = uploadDir.substring(0, uploadDir.length() - 1);         }

        if(filename.startsWith("/")) {

            filename = filename.substring(0, uploadDir.length() - 1);        }

        File desc = new File(uploadDir + "/" + filename);

        if(!desc.getParentFile().exists()) {

            desc.getParentFile().mkdirs();        }

        if(!desc.exists()) {

            desc.createNewFile();        }

        return desc;

    }

   

 

   public static final String extractFilename(MultipartFile file, String baseDir) throws UnsupportedEncodingException {

        String filename = file.getOriginalFilename();

        int slashIndex = filename.indexOf("/");

        if (slashIndex >= 0) {

            filename = filename.substring(slashIndex + 1);

        }

        filename = baseDir + "/" + filename;

        return filename;

    }

    public static final String extractUploadDir(HttpServletRequest request) {

        return request.getServletContext().getRealPath("/");

    }

}   

n上传的示例页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<form action="/mvcexample/fileope/upload" method="post" enctype="multipart/form-data">

file1:<input type="file"  name="myFile"/>

<br>

file2:<input type="file"  name="myFile"/>

<br>

<input type="submit" value="上传">

</form>

文件下载

n下载的示例Controller的方法

@RequestMapping(value = "download", method = RequestMethod.GET)

public static void download(HttpServletRequest request, 

      HttpServletResponse response, String fileName) throws Exception { 

  response.setContentType("text/html;charset=UTF-8"); 

  request.setCharacterEncoding("UTF-8"); 

  BufferedInputStream bis = null; 

  BufferedOutputStream bos = null; 

  String newFileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");

  String ctxPath = request.getSession().getServletContext() 

          .getRealPath("/")  + FileUploadUtils.defaultBaseDir; 

  String downLoadPath = ctxPath +"/"+ newFileName; 

  long fileLength = new File(downLoadPath).length(); 

  response.setHeader("Content-disposition", "attachment; filename="

          + new String(newFileName.getBytes("gb2312"), "ISO8859-1")); 

  response.setHeader("Content-Length", String.valueOf(fileLength)); 

  bis = new BufferedInputStream(new FileInputStream(downLoadPath)); 

  bos = new BufferedOutputStream(response.getOutputStream()); 

  byte[] buff = new byte[2048]; 

  int bytesRead; 

  while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { 

      bos.write(buff, 0, bytesRead); 

  } 

  bis.close();    bos.close();

}