Springboot 之文件上传下载

7 篇文章 0 订阅

JAVA SpringBoot学习之文件上传下载

客户端的图片下载分为两种,一种是以流的方式,一种是直接给个url地址进行展示。这里分别以两种方式记录,文件的上传下载

文件上传:

application.yml配置地址

fileConf:
	savePath: C:\workspace\pragrammerFile\
    visitPath: http://localhost:8760/

controller 部分:

  @Autowired
  FileService fileService;
  @Value("${fileConf.savePath}")
  private String fileSavePath;

  @Value("${fileConf.visitPath}")
  private String fileVisitPath;


@PostMapping("upload")
    public Json  upload(Long id,String type,String description,HttpServletRequest request) {
        Json json=Json.buildSuccessResult();
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile multipartFile=multipartRequest.getFile("file");
            String contentType = multipartFile.getContentType();  //文件类型
            String fileName = multipartFile.getOriginalFilename(); //名字
            String fileSuffix = fileName.substring(
                    fileName.lastIndexOf("."), fileName.length());
            UUID uuid = UUID.randomUUID();
            File savePath=new File(fileSavePath);//创建文件夹
            if (!savePath.exists()) {
                savePath.mkdirs();
            }
            String uuidFileName = uuid.toString() + fileSuffix;
            File file=new File(fileSavePath,uuidFileName);//拼接文件路径
            multipartFile.transferTo(file);//保存到本地,其实transferTo底层依然使用的是IO流操作的,这里自己写io也可以
            FileEntity fileEntity=new FileEntity();
            fileEntity.setFileDescription(description);
            fileEntity.setFileName(fileName);
            fileEntity.setSize(FileUtils.getFileSize(multipartFile));
            fileEntity.setFileType(contentType);
            fileEntity.setPath(uuidFileName);
            fileEntity.setUrl(fileVisitPath);
            fileEntity.setModelId(id);
            fileEntity.setModelType(type);
            fileService.saveFile(fileEntity);
        } catch (Exception e) {
            json.buildErrorResponse(ApplicationResponseCode.FAIL,e.getMessage());
        }
        return json;
   }

web端上传文件,我这里需要额外的参数id,type,description,所以要封装到FormData中进行传递

 let uploadData = new FormData();
      uploadData.append("file", file);
      uploadData.append("id", "12");
      uploadData.append("type", "News");
      uploadData.append("description", file.name);
      this.$putUploadFiles(uploadData, "/api/FileEntity/upload").then(
        response => {
          this.$success("上传成功");
      }
 );

下载文件
1.返回IO流

	if (fileName == null) {
            throw new BusinessException("1001", "文件名不能为空");
        }
 
        // 通过文件名查找文件信息
        FileInfo fileInfo = fileInfoDao.findByFileName(fileName);
        log.info("fileInfo-->{}", fileInfo);
        if (fileInfo == null) {
            throw new BusinessException("2001", "文件名不存在");
        }
 
        //设置响应头
        res.setContentType("application/force-download");// 设置强制下载不打开
        res.addHeader("Content-Disposition", "attachment;fileName=" +
                new String(fileInfo.getFileOriginName().getBytes("gbk"), "iso8859-1"));// 设置文件名
        res.setHeader("Context-Type", "application/xmsdownload");
 
        //判断文件是否存在
        File file = new File(Paths.get(fileInfo.getFilePath(), fileName).toString());
        if (file.exists()) {
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = res.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                log.info("下载成功");
            } catch (Exception e) {
                e.printStackTrace();
                throw new BusinessException("9999", e.getMessage());
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

2.直接返回url,
一般来说,想一些客户端,除非是一些非图片类型,一般是直接返回url的
第一步配置WebMvcConfigurer,

@Configuration
public class MyWebMvcConfigurerAdapter implements WebMvcConfigurer {
    private String fileSavePath="file:C:/workspace/pragrammerFile/";
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //指向外部目录
        registry.addResourceHandler("img/**").addResourceLocations(fileSavePath);
    }
}

其中fileSavePath:C:\workspace\pragrammerFile
而img就是虚拟的映射fileSavePat文件夹,所以最后完整地址就是
ip/img/文件名,
所以后端返回前端完整url即可,或者返回img/文件名,前端自己拼接

示例:
这里上传一张如下图片:
在这里插入图片描述

在这里插入图片描述
数据库:这里看到数据记录已经插入到文件表中。
在这里插入图片描述
接下来就去看C:\workspace\pragrammerFile\有没有文件生成
在这里插入图片描述
可以看到生成了文件。
下面直接在浏览器通过url+img/文件名去访问该图片,可以访问啦~
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是SpringBoot文件上传下载的步骤: 1. 创建SpringBoot项目并导入相关依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` 2. 在application.properties文件中配置文件保存路径: ```properties filePath=E:/springboot_save_file/ ``` 3. 创建文件上传的Controller: ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.io.File; import java.io.IOException; @Controller public class FileUploadController { @Value("${filePath}") private String filePath; @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) { if (file.isEmpty()) { redirectAttributes.addFlashAttribute("message", "Please select a file to upload"); return "redirect:/"; } try { String fileName = StringUtils.cleanPath(file.getOriginalFilename()); File destFile = new File(filePath + fileName); file.transferTo(destFile); redirectAttributes.addFlashAttribute("message", "File uploaded successfully"); } catch (IOException e) { e.printStackTrace(); redirectAttributes.addFlashAttribute("message", "Failed to upload file"); } return "redirect:/"; } } ``` 4. 创建文件下载的Controller: ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; @Controller public class FileDownloadController { @Value("${filePath}") private String filePath; @GetMapping("/download/{fileName:.+}") public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) { Path file = Paths.get(filePath + fileName); Resource resource; try { resource = new UrlResource(file.toUri()); } catch (IOException e) { e.printStackTrace(); return ResponseEntity.notFound().build(); } return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") .body(resource); } } ``` 5. 创建Thymeleaf模板文件index.html: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Spring Boot File Upload/Download</title> </head> <body> <h1>File Upload/Download</h1> <form method="post" action="/upload" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" value="Upload" /> </form> <p th:text="${message}"></p> <hr/> <h2>Download Files:</h2> <ul> <li th:each="file : ${files}"> <a th:href="@{/download/{fileName}(fileName=${file})}" th:text="${file}"></a> </li> </ul> </body> </html> ``` 6. 运行SpringBoot应用,并访问http://localhost:8080/,即可进行文件上传下载操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值