SpringBoot文件上传与下载

/**
 * file upload and download
 *
 * @author ley
 **/
@Slf4j
@Component
public class FileUploadUtils {

    /**
     * innovation file path
     **/
    @Value("${innovation.file.path}")
    private String uploadRootPath;


    @Value("${innovation.file.path}")
    private String downloadPath;

    /**
     * allow upload file suffix
     **/
     //此处格式可以有配置文件动态决定
    private final List<String> allowFiles = Arrays.asList(new String[]{
            "xls", "xlsx", "txt", "png", "doc", "docx", "pdf", "gif",
            "jpg", "jpeg", "bmp", "ppt"
    });


    /**
     * upload file and return file download path
     *
     * @param path upload relative path
     * @return return relative upload path
     * @see File#mkdirs()
     * @see File#mkdir()
     **/
    public String upload(MultipartFile file, String path) {
        String result = "";
        if (file == null) {
            return null;
        }
        String uploadFileName = "";
        String uploadRootPath = this.uploadRootPath;
        if (file.isEmpty()) {
            result = "文件未上传";
        } else {
            String _fileName = file.getOriginalFilename();
            //文件扩展名
            String suffix = _fileName.substring(_fileName.lastIndexOf(".") + 1);
            if (StringUtils.isNotBlank(suffix)) {
                if (isAllowUploadFile(suffix)) {

                    // 使用UUID生成文件名称
                    uploadFileName = UUID.randomUUID().toString() + "." + suffix;

                    String uploadPath = uploadRootPath + path;
                    log.info("开始上传文件,上传的文件名:{},上传的路径:{},新文件名:{}", _fileName, uploadPath, uploadFileName);

                    //判断上传路径是否存在
                    File uploadDir = new File(uploadPath);
                    if (!uploadDir.exists()) {
                        //使文件可以改,因为Tomcat发布服务后,文件的权限不一定是可以改的
                        uploadDir.setWritable(true);
                        //使用dirs是为了解决上传的路径中,如果有文件夹的没有创建,其会自动创建文件夹
                        uploadDir.mkdirs();
                    }


                    //上传文件
                    File restore = new File(uploadPath, uploadFileName);

                    try {
                        //方式1:使用MultipartFile的transferTo方法进行文件的复制
//                        file.transferTo(restore);

                        //方式2:使用commons-io 2.5包下的copyInputStreamToFile进行文件的复制
                        FileUtils.copyInputStreamToFile(file.getInputStream(), restore);
                        //返回存储文件的相对位置(配置nginx服务访问)
                        result = path + File.separator + uploadFileName;

                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    result = "文件格式不对,只能上传ppt、ptx、doc、docx、xls、xlsx、pdf、png、jpg、jpeg、gif、bmp格式.";
                }
            }
        }

        //返回新的文件相对路径
        return result;
    }


    /**
     * get file restore absolute path
     **/
    public String getFilePath(String path) {
        String fileAbsolutePath = this.uploadRootPath + path;
        return fileAbsolutePath;
    }


    /**
     * is allow upload file suffix
     **/
    private boolean isAllowUploadFile(String fileSuffix) {
        String fileSuffixLower = fileSuffix.toLowerCase();
        if (allowFiles.contains(fileSuffixLower)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * download file
     **/
    public String downloadFile(HttpServletResponse response, String fileName) {
        String fileNamePath = downloadPath + File.separator + fileName;
        File file = new File(fileNamePath);

        //如果文件不存在
        if (!file.exists()) {
            log.error("文件不存在!");
            return "文件不存在";
        }


        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //设置响应属性
            response.setContentType("application/x-download");
            response.addHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setCharacterEncoding("UTF-8");

            inputStream = new FileInputStream(file);
            outputStream = response.getOutputStream();
            //将文件输入流拷贝到响应输出流中
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();

            return "文件下载成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "文件下载出错";
        } finally {
            CloseUtils.close(inputStream, outputStream);
        }
    }


    /**
     * get upload root path
     **/
    public String getUploadRootPath() {
        return uploadRootPath;
    }
}

你好!关于Spring Boot和Vue文件上传下载的问题,我可以为你提供一些解答。 在Spring Boot中,你可以使用Spring MVC的文件上传功能来处理文件上传。首先,你需要在Spring Boot项目中配置一个文件上传的Bean。可以使用`MultipartResolver`接口来实现文件上传功能。下面是一个示例代码: ```java @Configuration public class WebConfig implements WebMvcConfigurer { @Bean public MultipartResolver multipartResolver() { return new StandardServletMultipartResolver(); } } ``` 接下来,你可以创建一个Controller来处理文件上传请求。你可以使用`@RequestParam`注解来接收上传的文件。以下是一个简单的上传文件的示例: ```java @RestController public class FileController { @PostMapping("/upload") public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) { // 处理文件上传逻辑 // 返回上传成功的消息 return ResponseEntity.ok("文件上传成功!"); } } ``` 在Vue中,你可以使用`axios`库来发送文件上传请求。以下是一个简单的文件上传的示例代码: ```javascript <template> <div> <input type="file" ref="fileInput" @change="uploadFile"> </div> </template> <script> import axios from 'axios'; export default { methods: { uploadFile() { const file = this.$refs.fileInput.files[0]; const formData = new FormData(); formData.append('file', file); axios.post('/upload', formData) .then(response => { // 处理上传成功的逻辑 console.log(response.data); }) .catch(error => { // 处理上传失败的逻辑 console.error(error); }); } } } </script> ``` 至于文件下载,你可以在Spring Boot中创建一个Controller来处理下载请求。你可以使用`ResponseEntity`来返回文件内容和正确的HTTP头。以下是一个简单的文件下载的示例: ```java @RestController public class FileController { @GetMapping("/download") public ResponseEntity<Resource> downloadFile() throws IOException { // 加载文件资源 Resource fileResource = new ClassPathResource("path/to/file.pdf"); // 设置HTTP头 HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=file.pdf"); return ResponseEntity.ok() .headers(headers) .body(fileResource); } } ``` 在Vue中,你可以使用`window.open`方法来下载文件。以下是一个简单的文件下载的示例代码: ```javascript <template> <div> <button @click="downloadFile">下载文件</button> </div> </template> <script> export default { methods: { downloadFile() { const downloadURL = '/download'; window.open(downloadURL, '_blank'); } } } </script> ``` 希望以上信息能够帮助到你!如果有任何问题,请随时问我。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值