栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springmvc文件上传与下载

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springmvc文件上传与下载

导入pom文件

 
    
      commons-fileupload
      commons-fileupload
      1.3.1
    
    
      commons-io
      commons-io
      2.5
    

xml配置

 
        
        
    

前端页面

文件上传

控制层部分

package com.zmc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
@Controller
@RequestMapping("/file")
public class FileController {
    

    @RequestMapping("/upload")
    public String upload(MultipartFile file, HttpServletRequest request, Model m) throws IOException {
//        (创建)设置文件上传目录 (项目内部)
        String uploadPath=request.getServletContext().getRealPath("uploadPath");
//       上传自定义电脑资源管理器
//        String uploadPath="D:/aaa";
//        判断目录是否存在,不存在就创建
        File file1=new File(uploadPath);
        if (!file1.exists()) {
            file1.mkdirs();
        }
//        获取文件原始名
        String originalName=file.getOriginalFilename();
//        获取文件后缀名
        String suffix=originalName.substring(originalName.lastIndexOf("."));
//        构建文件上传具体路径
        String detailPath=uploadPath.concat(File.separator).concat(UUID.randomUUID().toString()).concat(suffix);
        file.transferTo(new File(detailPath));
        m.addAttribute("detailPath",detailPath);
        return "success";
    }
}

文件下载

 @RequestMapping("/downLoad")
    public ResponseEntity downLoad(HttpServletRequest request, String fileName) throws IOException {
//        获取文件文件地址信息(在项目内部)
        String upload = request.getServletContext().getRealPath("upload");
//        拼接出具体路径,判断文件是否存在
        File file1 = new File(upload.concat(File.separator).concat(fileName));
        if (!file1.exists()) {
            return null;
        }
//        创建标头文件对象
        HttpHeaders headers = new HttpHeaders();
//        解决乱码问题
        String s = new String(fileName.getBytes(StandardCharsets.UTF_8), "iso-8859-1");
//        以下载方式打开文件
        headers.setContentDispositionFormData(s, fileName);
//        二进制流
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        return new ResponseEntity(FileUtils.readFileToByteArray(file1),headers, HttpStatus.CREATED);
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/582279.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号