文件的上传和下载,并以列表形式展现在浏览器端

首先,我的页面是这样的,大家可以参考;

一、文件的上传

1)前台(jsp页面)

a.     Form表单提交方式为post

b.    Enctype: multipart/form-data

c.     Input: type file

<body>
<form action="${pageContext.request.contextPath}/file/upload"
      method="post" enctype="multipart/form-data">
    请选择:<input type="file" name="file">
    <input type="submit" value="上传">
</form>
<table>
    <thead>
    <tr>
        <th>编号</th>
        <th>文件名</th>
        <th>文件大小</th>
        <th>缩略图</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <c:forEach items="${files}" var="file" varStatus="status">
        <tr>
            <td>${status.count}</td>
            <td>${file.name}</td>
            <td>${file.size}kb</td>
            <td><img style="width: 50px;height: 50px;"src="${pageContext.request.contextPath}/headpic/${file.name}"></td>
            <td><a href="${pageContext.request.contextPath}/file/download?path=${file.name}">下载</a></td>
        </tr>
    </c:forEach>
    </tbody>
</table>
</body>

2)后台

a、写一个FileItem的实体类,用来设置图片的一些信息;

package entity;
import java.io.Serializable;
public class FileItem implements Serializable {
    private String name;
    private Long size;
    public FileItem() {
    }
    public FileItem(String name, Long size) {
        this.name = name;
        this.size = size;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Long getSize() {
        return size;
    }
    public void setSize(Long size) {
        this.size = size;
    }
}

b、写一个控制层方法,使用MultipartFile 对象来接收上传的文件对象;

transferTo 保存上传的文件内容;

@Controller
@RequestMapping("/file")
public class AdminController {
    @RequestMapping("/list")
    public String listFiles(String path,ModelMap modelMap){
        System.out.println(path);
        File file=new File("E:/headpic");
        //列出该目录下所有的文件或文件夹
        File[] files = file.listFiles();
        List<FileItem> fileItemList=new ArrayList<>();
        for (File file1 : files) {
            if(file1.isFile()) {
                String name = file1.getName();
                long length = file1.length();
                FileItem fileItem = new FileItem(name, Math.round(length/1024.0+0.5));
                fileItemList.add(fileItem);
            }
        }
        modelMap.put("files",fileItemList);
        return "/list.jsp";
    }
    @RequestMapping("/upload")
    public String upload(MultipartFile file) throws IOException {
        if(file==null){
            throw new FileNotFoundException();
        }
        String filename = file.getOriginalFilename();
        File file1 = new File("E:/headpic", filename);
        if(!file1.getParentFile().exists()){
            file1.getParentFile().mkdirs();
        }
        //将文件保存到对应的目录
        file.transferTo(file1);
        return "redirect:list";
    }
}

c、配置文件:需要在springmvc的配置文件中配置 multipartResolver解析器;

    <!--配置文件上传-->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--设置文件编码格式-->
        <property name="defaultEncoding" value="UTF-8"/>
        <!--设置最大上传大小,以字节为单位-->
        <property name="maxUploadSize" value="10240000" />
    </bean>
    <!--资源映射,将请求地址映射到某个目录或具体的磁盘路径下-->
    <!-- mapping 配置请求地址,location 配置文件路径-->
    <!-- 请求地址 /head/logo.png ==>E:/headpic/logo.png-->
    <mvc:resources mapping="/headpic/**" location="file:E:/headpic/"></mvc:resources>

 

二、文件的下载

1)明确下载的内容。由前台请求传递需要下载的文件名或路径;

2)编写下载的后台控制层代码;

a.        根据前台请求数据,定位到需要下载的文件,File;

b.       设置响应的头部信息中setContentType 为Stream。

c.        设置响应头中设置以附件形式打开

d.       返回ResponseEntity对象,指定响应头,响应体内容(文件的字节数组),状态码;

    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(String path) throws IOException {
        File file=new File("E:/headpic",path);
        if(!file.exists()|| !file.isFile()){
            throw new FileNotFoundException("未找到文件:"+path);
        }
        HttpHeaders headers=new HttpHeaders();
        //设为返回的数据类型为二进制流
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //设置浏览器以附件形式打开下载
        headers.setContentDispositionFormData("attachment",file.getName());
        return new ResponseEntity<>(
                FileUtils.readFileToByteArray(file),//返回的字节内容
                headers,//头部信息
                HttpStatus.OK);//状态码
    }

 

posted @ 2020-07-06 22:39  等你的夏天  阅读(690)  评论(0编辑  收藏  举报