4.文件上传下载

发布于:2024-04-06 ⋅ 阅读:(24) ⋅ 点赞:(0)

一、配置文件

Spring
    #上传文件使用
    servlet:
      multipart:
        #单个文件最大上传大小
        max-file-size: 10MB
        #每次请求上传文件大小最大值
        max-request-size: 30MB
#自定义参数
define:
  nginx:
    path: D:\uploadFile\

二、service层

public interface FileService {
    void saveFile(byte[] file, String filePath, String fileName) throws Exception;

    void download(HttpServletResponse response, String filename, Model model);
}

三、serviceImpl层

@Service
public class FileServiceImpl implements FileService {

    private static final String UTF_8 = "UTF-8";

    @Value("${define.nginx.path}")
    private String nginxPath;


    @Override
    public void saveFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath + fileName);
        out.write(file);
        out.flush();
        out.close();
    }

    @Override
    public void download(HttpServletResponse response, String filename, Model model) {

        response.setContentType("application/force-download");
        response.setCharacterEncoding(UTF_8);
        // 设置下载后的文件名以及header
        response.addHeader("Content-disposition", "attachment;fileName=" + URLEncoder.encode(filename));
        byte[] buff = new byte[1024];
        //创建缓冲输入流
        BufferedInputStream bis = null;
        OutputStream outputStream = null;

        try {
            outputStream = response.getOutputStream();

            //这个路径为待下载文件的路径
            bis = new BufferedInputStream(new FileInputStream(new File(nginxPath + filename )));
            int read = bis.read(buff);

            //通过while循环写入到指定了的文件夹中
            while (read != -1) {
                outputStream.write(buff, 0, buff.length);
                outputStream.flush();
                read = bis.read(buff);
            }
        } catch ( IOException e ) {
            e.printStackTrace();
            //出现异常返回给页面失败的信息
            System.out.println("--------------------------------");
            model.addAttribute("result","下载失败");
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

四、controller层

@Api(tags = {"文件上传下载"})
@Controller
@RequestMapping("/upload")
public class UploadController {
    private static final String NULL_FILE = "";

    @Value("${define.nginx.path}")
    private String nginxPath;

    @Autowired
    private FileService fileService;

    @GetMapping(value = "/goToUpload")
    public String goToUploadHtml() {
        return "upload";
    }

    @ApiOperation("单文件上传")
    @PostMapping("/uploadFile")
    @ResponseBody
    public String singleFileUpload(@RequestParam("file") MultipartFile file) {
        try {
            if (file == null || NULL_FILE.equals(file.getOriginalFilename())) {
                return "upload failure";
            }
            fileService.saveFile(file.getBytes(), nginxPath, file.getOriginalFilename());
        } catch (Exception e) {
            return "upload failure";
        }
        return "upload success";
    }

    @ApiOperation("批量文件上传")
    @PostMapping("/uploadFiles")
    @ResponseBody
    public String multiFileUpload(@RequestParam("file") MultipartFile[] files) {
        try {

            for (int i = 0; i < files.length; i++) {
                //check file
                if (NULL_FILE.equals(files[i].getOriginalFilename())) {
                    continue;
                }
                fileService.saveFile(files[i].getBytes(), nginxPath, files[i].getOriginalFilename());
            }
        } catch (Exception e) {
            return "upload failure";
        }
        return "upload success";
    }


    @ApiOperation("文件下传")
    @PostMapping("/download")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "文件名",name = "fileName",dataType = "string")
    })
    public void  testDownload(HttpServletResponse response,String fileName , Model model) {
        fileService.download(response,fileName,model);

        //成功后返回成功信息
        model.addAttribute("result","下载成功");
    }


}

五、页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SpringBoot上传文件</title>
</head>
<body>
<!--单文件上传-->
<form enctype="multipart/form-data" method="post" action="http://localhost:8080/upload/uploadFile">
    图片:<input type="file" name="file"/>
    <input type="submit" value="上传"/>
</form>
<!--批量文件上传-->
<form enctype="multipart/form-data" method="post" action="http://localhost:8080/upload/uploadFiles">
    图片:<input type="file" name="file"/><br>
    图片:<input type="file" name="file"/><br>
    图片:<input type="file" name="file"/><br>
    <input type="submit" value="上传全部"/>
</form>
<!--文件下载-->
<form  action="http://localhost:8080/upload/download" method="post">
    <p><h1>下载文件</h1></p>
    <p><h2>1.png</h2></p>
    <p><input type="submit" value="下载"/></p>
</form>
</body>
</html>