设为首页 加入收藏

TOP

学习笔记——SpringMVC文件上传与下载(一)
2023-07-25 21:42:41 】 浏览:53
Tags:习笔记 SpringMVC 文件上

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.CommonsMultipa
首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇day07-Spring管理Bean-IOC-05 下一篇CountDownLatch的使用

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目