当前位置: 首页 > news >正文

SpringBoot2:web开发常用功能实现及原理解析-上传与下载

文章目录

  • 一、上传文件
    • 1、前端上传文件给Java接口
    • 2、Java接口上传文件给Java接口
  • 二、下载文件
    • 1、前端调用Java接口下载文件
    • 2、Java接口下载网络文件到本地
    • 3、前端调用Java接口下载网络文件

一、上传文件

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

Controller接口
此接口支持上传单个文件和多个文件,并保存在本地


import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;import java.io.File;
import java.io.IOException;/*** 文件上传测试*/
@Slf4j
@RestController
public class FileTestController {/*** MultipartFile 自动封装上传过来的文件* @param headerImg* @param photos* @return*/@PostMapping("/upload")public String upload(@RequestPart("headerImg") MultipartFile headerImg,@RequestPart("photos") MultipartFile[] photos) throws IOException {log.info("上传的信息:headerImg={},photos={}",headerImg.getSize(),photos.length);if(!headerImg.isEmpty()){//保存到文件服务器,OSS服务器String originalFilename = headerImg.getOriginalFilename();headerImg.transferTo(new File("E:\\workspace\\boot-05-web-01\\headerImg\\"+originalFilename));}if(photos.length > 0){for (MultipartFile photo : photos) {if(!photo.isEmpty()){String originalFilename = photo.getOriginalFilename();photo.transferTo(new File("E:\\workspace\\boot-05-web-01\\photos\\"+originalFilename));}}}return "OK";}}

yaml配置

spring:servlet:multipart:max-file-size: 10MB		单个文件最大值max-request-size: 100MB	单次请求上传文件最大值file-size-threshold: 4KB	内存中IO流,满4KB就开始写入磁盘

Postman调用传参
在这里插入图片描述

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

我这里是将前端接收过来的文件转发到另外一个接口,也就是一种上传操作。
如果,你要将本地文件上传过去,那么,修改下代码,读取本地文件,格式转化一下即可。

RestTemplateConfig

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;@Configuration
public class RestTemplateConfig {@Beanpublic RestTemplate restTemplate(){return new RestTemplate();}}

Java转发文件接口

	@PostMapping("/upload")public String upload(@RequestPart("headerImg") MultipartFile headerImg,@RequestPart("photos") MultipartFile[] photos) throws IOException {log.info("上传的信息:headerImg={},photos={}",headerImg.getSize(),photos.length);String url="http://127.0.0.1:8080//upload2";//封装请求头HttpHeaders httpHeaders = new HttpHeaders();httpHeaders.set("Content-Type", MediaType.MULTIPART_FORM_DATA_VALUE + ";charset=UTF-8");httpHeaders.set("test1", "1");httpHeaders.set("test2", "2");MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();//文件处理FileSystemResource headerImgFile = new FileSystemResource(multipartFile2File(headerImg));form.add("headerImg", headerImgFile);FileSystemResource[] photosArr = new FileSystemResource[photos.length];for (int i = 0; i < photos.length; i++) {photosArr[i] = new FileSystemResource(multipartFile2File(photos[i]));form.add("photos", photosArr[i]);}HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, httpHeaders);RestTemplate restTemplate = new RestTemplate();//发送请求String result = restTemplate.postForObject(url, files,String.class);return result;}private static File multipartFile2File(@NonNull MultipartFile multipartFile) {// 获取文件名String fileName = multipartFile.getOriginalFilename();// 获取文件前缀String prefix = fileName.substring(0, fileName.lastIndexOf("."));//获取文件后缀String suffix = fileName.substring(fileName.lastIndexOf("."));try {//生成临时文件//文件名字必须大于3,否则报错File file = File.createTempFile(prefix, suffix);//将原文件转换成新建的临时文件multipartFile.transferTo(file);file.deleteOnExit();return file;} catch (Exception e) {e.printStackTrace();}return null;}

Java接收文件接口

	@PostMapping("/upload2")public String upload2(@RequestPart("headerImg") MultipartFile headerImg,@RequestPart("photos") MultipartFile[] photos) throws IOException {if(!headerImg.isEmpty()){//保存到文件服务器,OSS服务器String originalFilename = headerImg.getOriginalFilename();headerImg.transferTo(new File("E:\\workspace\\boot-05-web-01\\headerImg\\"+originalFilename));}if(photos.length > 0){for (MultipartFile photo : photos) {if(!photo.isEmpty()){String originalFilename = photo.getOriginalFilename();photo.transferTo(new File("E:\\workspace\\boot-05-web-01\\photos\\"+originalFilename));}}}return "upload2 OK";}

二、下载文件

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

Controller

import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;@Slf4j
@RestController
public class FileTestController {private static final String FILE_DIRECTORY = "E:\\workspace\\boot-05-web-01\\photos";@GetMapping("/files/{fileName:.+}")public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) throws IOException {Path filePath = Paths.get(FILE_DIRECTORY).resolve(fileName).normalize();Resource resource = new FileUrlResource(String.valueOf(filePath));if (!resource.exists()) {throw new FileNotFoundException("File not found " + fileName);}// 设置下载文件的响应头HttpHeaders headers = new HttpHeaders();headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");return ResponseEntity.ok().headers(headers).body(resource);}}

测试方法:
浏览器直接发送get请求即可
http://127.0.0.1:8080/files/andriod1749898216865912222.jpg

2、Java接口下载网络文件到本地

Controller

	@GetMapping("/downloadNetFileToLocal")public Object downloadNetFileToLocal(@RequestParam("url") String fileUrl) throws Exception {JSONObject result = new JSONObject();String fileName = fileUrl.split("/")[fileUrl.split("/").length-1];URL url = new URL(fileUrl);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");connection.setConnectTimeout(5000);InputStream inputStream = connection.getInputStream();FileOutputStream fileOutputStream = new FileOutputStream("E:\\workspace\\boot-05-web-01\\photos\\"+fileName);byte[] buffer = new byte[1024];int byteread;int bytesum = 0;while ((byteread = inputStream.read(buffer)) != -1){bytesum += byteread;fileOutputStream.write(buffer,0,byteread);}fileOutputStream.close();result.put("bytes",bytesum);result.put("code",200);return result.toString();}

测试地址:
http://127.0.0.1:8080/downloadNetFileToLocal?url=https://img-blog.csdnimg.cn/166e183e84094c44bbc8ad66500cef5b.jpeg

3、前端调用Java接口下载网络文件

	@GetMapping("/downloadNetFile")public ResponseEntity<?> downloadNetFile(@RequestParam("url") String fileUrl) throws Exception {String fileName = fileUrl.split("/")[fileUrl.split("/").length-1];URL url = new URL(fileUrl);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");connection.setConnectTimeout(5000);InputStream inputStream = connection.getInputStream();byte[] bytes = streamToByteArray(inputStream);HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);headers.setContentLength(bytes.length);headers.setContentDispositionFormData("attachment", fileName);return new ResponseEntity<>(bytes, headers, HttpStatus.OK);}/*** 功能:将输入流转换成 byte[]** @param is* @return* @throws Exception*/public static byte[] streamToByteArray(InputStream is) throws Exception {ByteArrayOutputStream bos = new ByteArrayOutputStream();//创建输出流对象byte[] b = new byte[1024];int len;while ((len = is.read(b)) != -1) {bos.write(b, 0, len);}byte[] array = bos.toByteArray();bos.close();return array;}

测试地址:http://127.0.0.1:8080/downloadNetFile?url=https://img-blog.csdnimg.cn/166e183e84094c44bbc8ad66500cef5b.jpeg

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • Activiti7《第二式:破剑式》——工作流中的以柔克刚
  • Win32 Wmi获取设备信息
  • VMware Workstation Player虚拟机Ubuntu启用Windows共享目录
  • 代码随想录八股训练营第四十天| C++
  • Leetcode Hot 100刷题记录 -Day14(矩阵置0)
  • Nacos未授权访问
  • 大工程师插件下载 官方地址
  • 【数据结构】十大经典排序算法总结与分析
  • Vue3.0组合式API:computed计算属性、watch监听器、watchEffect高级监听器
  • C++ 常用设计模式
  • 有源滤波器UAF42
  • Golang协程泄漏定位和排查
  • 项目小总结
  • 在CentOS上搭建NFS服务器
  • rtmp推流
  • JAVA多线程机制解析-volatilesynchronized
  • React Native移动开发实战-3-实现页面间的数据传递
  • Redis 中的布隆过滤器
  • sublime配置文件
  • Vue 动态创建 component
  • 百度地图API标注+时间轴组件
  • 关于Android中设置闹钟的相对比较完善的解决方案
  • 解析带emoji和链接的聊天系统消息
  • 紧急通知:《观止-微软》请在经管柜购买!
  • 让你成为前端,后端或全栈开发程序员的进阶指南,一门学到老的技术
  • 人脸识别最新开发经验demo
  • 我的业余项目总结
  • 新手搭建网站的主要流程
  • 一些css基础学习笔记
  • MiKTeX could not find the script engine ‘perl.exe‘ which is required to execute ‘latexmk‘.
  • ​flutter 代码混淆
  • #我与Java虚拟机的故事#连载03:面试过的百度,滴滴,快手都问了这些问题
  • #我与Java虚拟机的故事#连载05:Java虚拟机的修炼之道
  • #周末课堂# 【Linux + JVM + Mysql高级性能优化班】(火热报名中~~~)
  • $().each和$.each的区别
  • $.proxy和$.extend
  • (17)Hive ——MR任务的map与reduce个数由什么决定?
  • (2022版)一套教程搞定k8s安装到实战 | RBAC
  • (ibm)Java 语言的 XPath API
  • (蓝桥杯每日一题)love
  • (十二)devops持续集成开发——jenkins的全局工具配置之sonar qube环境安装及配置
  • (十六)串口UART
  • (转)拼包函数及网络封包的异常处理(含代码)
  • (转)人的集合论——移山之道
  • (自用)网络编程
  • ./include/caffe/util/cudnn.hpp: In function ‘const char* cudnnGetErrorString(cudnnStatus_t)’: ./incl
  • .Net core 6.0 升8.0
  • .NET Framework 4.6.2改进了WPF和安全性
  • .NET 设计模式初探
  • .NET 中使用 Mutex 进行跨越进程边界的同步
  • .NET开源项目介绍及资源推荐:数据持久层
  • [ Linux ] git工具的基本使用(仓库的构建,提交)
  • [ 蓝桥杯Web真题 ]-Markdown 文档解析
  • [ 云计算 | AWS ] AI 编程助手新势力 Amazon CodeWhisperer:优势功能及实用技巧
  • [20150629]简单的加密连接.txt