spring下载上传文件

下载文件

@GetMapping("downloadImg")
public ResponseEntity<byte[]> downloadImg(HttpServletRequest request) {
    String realPath = request.getServletContext().getRealPath("upload/2.jpg");
    byte[] bytes;
    try {
        FileInputStream fileInputStream = new FileInputStream(realPath);
        bytes = new byte[fileInputStream.available()];
        int read = fileInputStream.read(bytes);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    //告知浏览器,我的流是一个 附件 (文件),浏览器触发下载
    HttpHeaders httpHeaders = new HttpHeaders();
    String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
    System.out.println(fileName);
    httpHeaders.setContentDispositionFormData("attachment", fileName);
    //返回对象
    ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);
    return responseEntity;
}

乱码解决:获取文件名的时候,将文件名转为utf-8格式:

String encode = URLEncoder.encode(fileName, "UTF-8");

下载rar文件如下:

@GetMapping("downLoadTxt")
    public ResponseEntity<byte[]> downLoadTxt(HttpServletRequest request){
        //获取要下载的文件地址
        String realPath = request.getServletContext().getRealPath("upload/新建文本文档.txt");
        byte[] bytes;
        String fileName;
        try {
            //将文件转为字节流对象
            FileInputStream fileInputStream = new FileInputStream(realPath);
            //定义接收字节流对象的数组
            bytes = new byte[fileInputStream.available()];
            //读取字节流
            int read = fileInputStream.read(bytes);
            //获取文件名并且将文件名编码格式改为utf-8
            fileName = URLEncoder.encode(realPath.substring(realPath.lastIndexOf("\\")+1),"UTF-8");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //告诉浏览器,出发下载
        HttpHeaders httpHeaders = new HttpHeaders();
        //设置浏览器下载附件,传入文件名
        httpHeaders.setContentDispositionFormData("attachment",fileName);
        //返回响应实体,字节流数组,下载附件,状态
        return new ResponseEntity<byte[]>(bytes,httpHeaders,HttpStatus.OK);
    }

文件上传:

单个文件上传:

@PostMapping("/myUpload")
public String upload(HttpServletRequest request) {
    String upload = request.getServletContext().getRealPath("/upload");
    File file = new File(upload);
    if (!file.exists()) file.mkdirs();
    try {
        Part uploadFile = request.getPart("file");
        String submittedFileName = uploadFile.getSubmittedFileName();
        uploadFile.write(upload + new Date().getTime() + submittedFileName);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (ServletException e) {
        throw new RuntimeException(e);
    }
    request.setAttribute("msg", "上传成功");
    return "forward:/pages/success.jsp";
}

@PostMapping("/file")//http://localhost:8088/file
public String uploadFile(@RequestBody MultipartFile file, HttpServletRequest request) throws IOException {
    //获取存储的绝对路径,此处放到img目录下面
    String realPath = request.getServletContext().getRealPath("upload/");
    //获取文件名
    String originalFilename = file.getOriginalFilename();
    //文件传输
    file.transferTo(Paths.get(realPath + new Date().getTime() + originalFilename));
    request.setAttribute("msg", "上传成功");
    return "/pages/success.jsp";
}
@PostMapping("/file")//http://localhost:8088/file
public String uploadFile(@RequestBody MultipartFile file, HttpServletRequest request) throws IOException {
    //获取存储的绝对路径,此处放到img目录下面
    String realPath = request.getServletContext().getRealPath("upload/");
    //获取文件名
    String originalFilename = file.getOriginalFilename();
    //文件传输
    file.transferTo(Paths.get(realPath + new Date().getTime() + originalFilename));
    request.setAttribute("msg", "上传成功");
    return "/pages/success.jsp";
}

多个文件上传:

@PostMapping("uploadMore")
public String uploadMore(HttpServletRequest request) throws ServletException, IOException {
    String realPath = request.getServletContext().getRealPath("/upload/");
    File file = new File(realPath);
    if (!file.exists()) file.mkdirs();
    Collection<Part> parts = request.getParts();
    parts.forEach(part -> {
        String fileName = part.getSubmittedFileName();//获取文件上传的名字
        String dir = disClose(fileName, realPath);//文件打散
        try {
            part.write(dir + fileName);//文件上传的位置
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });
    return "pages/success.jsp";
}

private String disClose(String fileName, String savePath) {
    //获取文件名hashcode的值,得到filename在内存中的地址
    int hashcode = fileName.hashCode();
    int dir1 = hashcode & 0xf;
    int dir2 = (hashcode & 0xf0) >> 4;
    String dir = savePath + "\\" + dir1 + "\\";
    File file = new File(dir);
    if (!file.exists()) file.mkdirs();
    System.out.println(dir);
    return dir;
}
posted @ 2023-03-06 15:52  Liku007  阅读(22)  评论(0编辑  收藏  举报