Java Web 学习(8) —— Spring MVC 之文件上传与下载

Spring MVC 之文件上传与下载

上传文件

表单

<form action="upload" enctype="multipart/form-data" method="post">
<input type="file" name="files" multiple/> 
<input type="submit" value="Upload" />
</form>

表单的编码类型为multipart/form-data,表单中必须包含类型为file的元素,它会显示成一个按钮,点击时,打开一个对话框,用来选择文件。
如果上传多个文件,可添加multiple属性。

上传的文件会被包在一个MultipartFile对象中。

public interface MultipartFile extends InputStreamSource {
    String getName();

    @Nullable
    String getOriginalFilename();

    @Nullable
    String getContentType();

    boolean isEmpty();

    long getSize();

    byte[] getBytes() throws IOException;

    @Override
    InputStream getInputStream() throws IOException;

    default Resource getResource() {
        return new MultipartFileResource(this);
    }

    void transferTo(File dest) throws IOException, IllegalStateException;
    
    default void transferTo(Path dest) throws IOException, IllegalStateException {
        FileCopyUtils.copy(getInputStream(), Files.newOutputStream(dest));
    }

}

控制器

@RequestMapping("upload")
@ResponseBody
public String uploadFile (MultipartFile[] files, HttpServletRequest request)
    throws IllegalStateException, IOException {
    String path = request.getServletContext().getRealPath("/files");
    for (MultipartFile file : files) {
        String name = file.getOriginalFilename();
        File f = new File(path, name);
        file.transferTo(f);
    }

    return "fin";
}

配置

<bean id="multipartResolver"
  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <!-- 上传文件最大 10MB -->
  <property name="maxUploadSize"> 
    <value>10485760</value> 
  </property> 
</bean>

依赖:commons-fileupload

下载文件

@RequestMapping("download")
public void downloadFile (@RequestParam String name, HttpServletRequest request, HttpServletResponse response) 
    throws IOException {
    String path = request.getServletContext().getRealPath("/files");
    File file = new File(path, name);
    Path filepath = file.toPath();
    response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
    // response.setContentType
    Files.copy(filepath, response.getOutputStream());
}





参考资料:《Spring MVC 学习指南》 Paul Deck 著

猜你喜欢

转载自www.cnblogs.com/JL916/p/11908823.html