第六天:SpringMVC文件上传和下载

(一)文件的上传

1、前端代码

页面上,文件上传三要素:

(1) form表单method必须是post

(2) form表单的enctype必须是multipart/form-data

(3) 表单中必须含有一个type=file的上传文件项

 

<%--  multiple="multiple" 多选 --%>
<form action="${pageContext.request.contextPath}/demo3001" method="post" enctype="multipart/form-data">
<input type="file" name="fileInfo" multiple="multiple">
<button>提交</button>
</form>

>

 

2、后端代码

1)引入坐标

<dependency>

<groupId>commons-fileupload</groupId>

<artifactId>commons-fileupload</artifactId>

<version>1.4</version>

</dependency>

 

2)在SpringMVC.xml中添加配置

<!--配置文件上传解析器,他会将上传的文件进行封装,

这个id是定死的,不能随便写,SpringMVC会调用它-->

<bean id="multipartResolver"

class="org.Springframework.web.multipart.commons.CommonsMultipartResolver">

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

</bean>

 

3)编写文件上传业务代码

单个文件上传

//上传文件解析器将上传上来的文件封装进这个对象

//参数名字不能随便写,对应请求表单中的file域的name

@RequestMapping("upload")

private void upload(MultipartFile uploadfile) throws IOException {

//指定上传路径

File file = new File("C:/upload");

//指定上传后的文件名称

String newFileName = UUID.randomUUID()+uploadfile.getOriginalFilename();

//文件上传

uploadfile.transferTo(new File(file,newFileName));

}

 

4)多文件上传

页面中:<input type="file" multiple name="uploadfile">

private void upload(MultipartFile[] uploadfiles) throws IOException {

//指定上传路径

File file = new File("C:/upload");

for (MultipartFile multipartFile : uploadfiles) {

//指定上传后的文件名称

String newFileName = UUID.randomUUID() + multipartFile.getOriginalFilename();

//文件上传

multipartFile.transferTo(new File(file, newFileName));

}

}

(二)文件的下载

Spring文件下载使用内部工具类 ResponseEntity完成

制作文件下载控制器方法

@RequestMapping("downloadFile")

public ResponseEntity<byte[]> downloadFile() throws Exception{

String fileName = "2018年上半年绩效考核.xls";

String path = "C:\upload\";

String newFileName = new String(fileName.getBytes("gbk"),"iso-8859-1");

File file = new File(path + fileName);

// 设置我们文件的响应头

HttpHeaders header = new HttpHeaders();

//指定输出的文件名称(硬编码以后的文件的名称)

header.setContentDispositionFormData("attachment",newFileName);

    //设置我们的响应类型(MIME:texthtml applicationjson textxml imagejpeg)

header.setContentType(MediaType.APPLICATION_OCTET_STREAM);        

    //利用SpringMVC的工具将我们指定的File对象中文件编译成字节数组

    return

new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),header,HttpStatus.OK);

}

原文地址:https://www.cnblogs.com/masterhxh/p/13859474.html