ToB企服应用市场:ToB评测及商务社交产业平台

标题: SpringBoot2:web开辟常用功能实现及原明白析-上传与下载 [打印本页]

作者: 老婆出轨    时间: 2024-9-21 02:23
标题: SpringBoot2:web开辟常用功能实现及原明白析-上传与下载
一、上传文件

1、前端上传文件给Java接口

Controller接口
此接口支持上传单个文件和多个文件,并保存在本地
  1. import lombok.extern.slf4j.Slf4j;
  2. import org.springframework.web.bind.annotation.PostMapping;
  3. import org.springframework.web.bind.annotation.RequestPart;
  4. import org.springframework.web.bind.annotation.RestController;
  5. import org.springframework.web.multipart.MultipartFile;
  6. import java.io.File;
  7. import java.io.IOException;
  8. /**
  9. * 文件上传测试
  10. */
  11. @Slf4j
  12. @RestController
  13. public class FileTestController {
  14.         /**
  15.          * MultipartFile 自动封装上传过来的文件
  16.          * @param headerImg
  17.          * @param photos
  18.          * @return
  19.          */
  20.         @PostMapping("/upload")
  21.         public String upload(
  22.                                                  @RequestPart("headerImg") MultipartFile headerImg,
  23.                                                  @RequestPart("photos") MultipartFile[] photos) throws IOException {
  24.                 log.info("上传的信息:headerImg={},photos={}",
  25.                                 headerImg.getSize(),photos.length);
  26.                 if(!headerImg.isEmpty()){
  27.                         //保存到文件服务器,OSS服务器
  28.                         String originalFilename = headerImg.getOriginalFilename();
  29.                         headerImg.transferTo(new File("E:\\workspace\\boot-05-web-01\\headerImg\"+originalFilename));
  30.                 }
  31.                 if(photos.length > 0){
  32.                         for (MultipartFile photo : photos) {
  33.                                 if(!photo.isEmpty()){
  34.                                         String originalFilename = photo.getOriginalFilename();
  35.                                         photo.transferTo(new File("E:\\workspace\\boot-05-web-01\\photos\"+originalFilename));
  36.                                 }
  37.                         }
  38.                 }
  39.                 return "OK";
  40.         }
  41. }
复制代码
yaml配置
  1. spring:
  2.   servlet:
  3.     multipart:
  4.       max-file-size: 10MB                单个文件最大值
  5.       max-request-size: 100MB        单次请求上传文件最大值
  6.       file-size-threshold: 4KB        内存中IO流,满4KB就开始写入磁盘
复制代码
Postman调用传参

2、Java接口上传文件给Java接口

我这里是将前端吸收过来的文件转发到别的一个接口,也就是一种上传利用。
如果,你要将本地文件上传过去,那么,修改下代码,读取本地文件,格式转化一下即可。
RestTemplateConfig
  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.web.client.RestTemplate;
  4. @Configuration
  5. public class RestTemplateConfig {
  6.         @Bean
  7.         public RestTemplate restTemplate(){
  8.                 return new RestTemplate();
  9.         }
  10. }
复制代码
Java转发文件接口
  1.         @PostMapping("/upload")
  2.         public String upload(
  3.                                                  @RequestPart("headerImg") MultipartFile headerImg,
  4.                                                  @RequestPart("photos") MultipartFile[] photos) throws IOException {
  5.                 log.info("上传的信息:headerImg={},photos={}",
  6.                                 headerImg.getSize(),photos.length);
  7.                 String url="http://127.0.0.1:8080//upload2";
  8.                 //封装请求头
  9.                 HttpHeaders httpHeaders = new HttpHeaders();
  10.                 httpHeaders.set("Content-Type", MediaType.MULTIPART_FORM_DATA_VALUE + ";charset=UTF-8");
  11.                 httpHeaders.set("test1", "1");
  12.                 httpHeaders.set("test2", "2");
  13.                 MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
  14.                 //文件处理
  15.                 FileSystemResource headerImgFile = new FileSystemResource(multipartFile2File(headerImg));
  16.                 form.add("headerImg", headerImgFile);
  17.                 FileSystemResource[] photosArr = new FileSystemResource[photos.length];
  18.                 for (int i = 0; i < photos.length; i++) {
  19.                         photosArr[i] = new FileSystemResource(multipartFile2File(photos[i]));
  20.                         form.add("photos", photosArr[i]);
  21.                 }
  22.                 HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, httpHeaders);
  23.                 RestTemplate restTemplate = new RestTemplate();
  24.                 //发送请求
  25.                 String result = restTemplate.postForObject(url, files,String.class);
  26.                 return result;
  27.         }
  28.        
  29.         private static File multipartFile2File(@NonNull MultipartFile multipartFile) {
  30.                 // 获取文件名
  31.                 String fileName = multipartFile.getOriginalFilename();
  32.                 // 获取文件前缀
  33.                 String prefix = fileName.substring(0, fileName.lastIndexOf("."));
  34.                 //获取文件后缀
  35.                 String suffix = fileName.substring(fileName.lastIndexOf("."));
  36.                 try {
  37.                         //生成临时文件
  38.                         //文件名字必须大于3,否则报错
  39.                         File file = File.createTempFile(prefix, suffix);
  40.                         //将原文件转换成新建的临时文件
  41.                         multipartFile.transferTo(file);
  42.                         file.deleteOnExit();
  43.                         return file;
  44.                 } catch (Exception e) {
  45.                         e.printStackTrace();
  46.                 }
  47.                 return null;
  48.         }
复制代码
Java吸收文件接口
  1.         @PostMapping("/upload2")
  2.         public String upload2(
  3.                         @RequestPart("headerImg") MultipartFile headerImg,
  4.                         @RequestPart("photos") MultipartFile[] photos) throws IOException {
  5.                         if(!headerImg.isEmpty()){
  6.                                 //保存到文件服务器,OSS服务器
  7.                                 String originalFilename = headerImg.getOriginalFilename();
  8.                                 headerImg.transferTo(new File("E:\\workspace\\boot-05-web-01\\headerImg\"+originalFilename));
  9.                         }
  10.                         if(photos.length > 0){
  11.                                 for (MultipartFile photo : photos) {
  12.                                         if(!photo.isEmpty()){
  13.                                                 String originalFilename = photo.getOriginalFilename();
  14.                                                 photo.transferTo(new File("E:\\workspace\\boot-05-web-01\\photos\"+originalFilename));
  15.                                         }
  16.                                 }
  17.                         }
  18.                         return "upload2 OK";
  19.         }
复制代码
二、下载文件

1、前端调用Java接口下载文件

Controller
  1. import org.springframework.core.io.Resource;
  2. import org.springframework.http.HttpHeaders;
  3. import org.springframework.http.ResponseEntity;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.PathVariable;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
  9. import java.io.IOException;
  10. import java.nio.file.Files;
  11. import java.nio.file.Path;
  12. import java.nio.file.Paths;
  13. @Slf4j
  14. @RestController
  15. public class FileTestController {
  16.         private static final String FILE_DIRECTORY = "E:\\workspace\\boot-05-web-01\\photos";
  17.         @GetMapping("/files/{fileName:.+}")
  18.         public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) throws IOException {
  19.                 Path filePath = Paths.get(FILE_DIRECTORY).resolve(fileName).normalize();
  20.                 Resource resource = new FileUrlResource(String.valueOf(filePath));
  21.                 if (!resource.exists()) {
  22.                         throw new FileNotFoundException("File not found " + fileName);
  23.                 }
  24.                 // 设置下载文件的响应头
  25.                 HttpHeaders headers = new HttpHeaders();
  26.                 headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="" + fileName + """);
  27.                 return ResponseEntity.ok()
  28.                                 .headers(headers)
  29.                                 .body(resource);
  30.         }
  31. }
复制代码
测试方法:
浏览器直接发送get请求即可
http://127.0.0.1:8080/files/andriod1749898216865912222.jpg
2、Java接口下载网络文件到本地

Controller
  1.         @GetMapping("/downloadNetFileToLocal")
  2.         public Object downloadNetFileToLocal(@RequestParam("url") String fileUrl) throws Exception {
  3.                 JSONObject result = new JSONObject();
  4.                 String fileName = fileUrl.split("/")[fileUrl.split("/").length-1];
  5.                 URL url = new URL(fileUrl);
  6.                 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  7.                 connection.setRequestMethod("GET");
  8.                 connection.setConnectTimeout(5000);
  9.                 InputStream inputStream = connection.getInputStream();
  10.                 FileOutputStream fileOutputStream = new FileOutputStream("E:\\workspace\\boot-05-web-01\\photos\"+fileName);
  11.                 byte[] buffer = new byte[1024];
  12.                 int byteread;
  13.                 int bytesum = 0;
  14.                 while ((byteread = inputStream.read(buffer)) != -1){
  15.                         bytesum += byteread;
  16.                         fileOutputStream.write(buffer,0,byteread);
  17.                 }
  18.                 fileOutputStream.close();
  19.                 result.put("bytes",bytesum);
  20.                 result.put("code",200);
  21.                 return result.toString();
  22.         }
复制代码
测试地址:
http://127.0.0.1:8080/downloadNetFileToLocal?url=https://img-blog.csdnimg.cn/166e183e84094c44bbc8ad66500cef5b.jpeg
3、前端调用Java接口下载网络文件

  1.         @GetMapping("/downloadNetFile")
  2.         public ResponseEntity<?> downloadNetFile(@RequestParam("url") String fileUrl) throws Exception {
  3.                 String fileName = fileUrl.split("/")[fileUrl.split("/").length-1];
  4.                 URL url = new URL(fileUrl);
  5.                 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  6.                 connection.setRequestMethod("GET");
  7.                 connection.setConnectTimeout(5000);
  8.                 InputStream inputStream = connection.getInputStream();
  9.                 byte[] bytes = streamToByteArray(inputStream);
  10.                 HttpHeaders headers = new HttpHeaders();
  11.                 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
  12.                 headers.setContentLength(bytes.length);
  13.                 headers.setContentDispositionFormData("attachment", fileName);
  14.                 return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
  15.         }
  16.         /**
  17.          * 功能:将输入流转换成 byte[]
  18.          *
  19.          * @param is
  20.          * @return
  21.          * @throws Exception
  22.          */
  23.         public static byte[] streamToByteArray(InputStream is) throws Exception {
  24.                 ByteArrayOutputStream bos = new ByteArrayOutputStream();//创建输出流对象
  25.                 byte[] b = new byte[1024];
  26.                 int len;
  27.                 while ((len = is.read(b)) != -1) {
  28.                         bos.write(b, 0, len);
  29.                 }
  30.                 byte[] array = bos.toByteArray();
  31.                 bos.close();
  32.                 return array;
  33.         }
复制代码
测试地址:http://127.0.0.1:8080/downloadNetFile?url=https://img-blog.csdnimg.cn/166e183e84094c44bbc8ad66500cef5b.jpeg

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4