2023-01-21

一、文件下载

1、实现文件下载步骤

(1)准备文件下载相关步骤

(2)将ResponseEntity<T>对象,作为方法返回值

(3)为ResponseEntity<T>对象,设置三个参数

2、示例代码

@RequestMapping("/fileDownloadController")
    public ResponseEntity<byte[]> fileDownload(HttpServletRequest request,String filename){
        ResponseEntity<byte[]> responseEntity = null;
        try {
            //获取文件位置
            //获取文件真实路径【(request|session)->ServletContext】
            String realPath = request.getServletContext().getRealPath("/WEB-INF/download/" + filename);
            //输入流
            InputStream is = new FileInputStream(realPath);
            //文件下载
            byte[] bytes = new byte[is.available()];
            is.read(bytes);
            //设置响应头
            HttpHeaders headers = new HttpHeaders();
            //设置要下载的文件的名字(及文件格式为附件格式,通知服务器下载当前资源,而不是打开)
            headers.add("Content-Disposition","attachment;filename");
            //处理中文文件名问题
            headers.setContentDispositionFormData("attachment",new String(filename));
            //状态码
            responseEntity = new ResponseEntity<>(bytes,headers, HttpStatus.OK);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseEntity;
    }

二、文件上传

1、实现文件上传思路

(1)准备工作

①准备文件上传页面

表单的提交方式必须为POST

设置表单enctype属性值为multipart/form-data

表单中包含文件域(type=file)

②导入jar包

<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>

③装配解析器:CommonsMultipartResolver

<!--    装配CommonsMultipartResolver-->
    <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
<!--        设置字符集-->
        <property name="defaultEncoding" value="utf-8"></property>
<!--        设置总文件的大小-->
        <property name="maxUploadSize" value="102400"></property>
    </bean>

(2)实现步骤

①将type=file(文件域)直接入参:MultipartFile类型即可

②获取文件名称

@Controller
public class FileUploadController {
    @RequestMapping("/fileUploadController")
    public String fileUploadController(String username,
                                       MultipartFile updateFile,
                                       HttpSession session){
        try {
            //获取文件名称
            String filename = updateFile.getOriginalFilename();
            //获取上传路径
            String realPath = session.getServletContext().getRealPath("/WEB-INF/upload");
            //判断上传路径是否存在(如不存在,创建)
            File filePath = new File(realPath);
            if(!filePath.exists()){
                filePath.mkdirs();
            }
            //实现文件上传
            //File.separator:是系统默认的分隔符
            File uFile = new File(filePath+File.separator+filename);
            updateFile.transferTo(uFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }
}

三、文件上传优化

1、允许同名文件上传

(1)使用UUID解决文件名重复问题

UUID是一个32位16进制随机数(特点:唯一性)

//实现文件上传
            //解决重复文件名上传的方式
            String uuid = UUID.randomUUID().toString().replace("-", "");
            //File.separator:是系统默认的分隔符
            File uFile = new File(filePath+File.separator+uuid+filename);

(2)使用时间戳解决文件名重复问题

System.currentTimeMillis()

2、设置上传文件大小上限

在装配CommonsMultipartResolver时,设置上传文件的上限

<!--    装配CommonsMultipartResolver-->
    <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
<!--        设置字符集-->
        <property name="defaultEncoding" value="utf-8"></property>
<!--        设置总文件的大小-->
        <property name="maxUploadSize" value="102400"></property>
    </bean>
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。