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

厦门网站建设 智多星常州seo收费

厦门网站建设 智多星,常州seo收费,自建网站服务器备案,做家教的网站Spring Boot中文件上传 前言 本篇主要参考Spring官方文档,整理了Spring Boot中文件上传如何实现,以及在代码中使用RestTemplate和HttpClient两种方式实现文件上传。 创建Spring Boot项目 首先创建一个Spring Boot Web项目,使用的Spring B…

Spring Boot中文件上传

前言

本篇主要参考Spring官方文档,整理了Spring Boot中文件上传如何实现,以及在代码中使用RestTemplate和HttpClient两种方式实现文件上传。

创建Spring Boot项目

首先创建一个Spring Boot Web项目,使用的Spring Boot版本为2.6.14,项目的pom文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.yzh</groupId><artifactId>uploadFile</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.6.14</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpmime</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><scope>test</scope></dependency></dependencies>
</project>

主要功能

提供下面三个功能:

方法URL功能
POST/upload上传文件
GET/files获取文件列表
GET/files/{fileName}下载文件

具体实现

代码结构

在这里插入图片描述

主要功能实现

这边直接贴一下代码:

controller

/*** 文件上传** @author yuanzhihao* @since 2023/3/22*/
@RestController
@RequestMapping
public class FileUploadController {@Autowiredprivate FileUploadService fileUploadService;/*** 上传文件** @param files 文件* @return 响应消息*/@PostMapping("/upload")public ResponseEntity<String> upload(@RequestParam("files") MultipartFile[] files) {fileUploadService.upload(files);return ResponseEntity.ok("File Upload Success");}/*** 获取文件列表** @return 文件列表*/@GetMapping("/files")public ResponseEntity<List<FileInfo>> list() {return ResponseEntity.ok(fileUploadService.list());}/*** 获取指定文件** @param fileName 文件名称* @return 文件*/@GetMapping("/files/{fileName:.+}")public ResponseEntity<Resource> getFile(@PathVariable("fileName") String fileName) {return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename=\"" + fileName + "\"").body(fileUploadService.getFile(fileName));}
}

service

/*** 文件上传Service** @author yuanzhihao* @since 2023/3/27*/
public interface FileUploadService {void upload(MultipartFile[] files);List<FileInfo> list();Resource getFile(String fileName);
}
/*** 文件上传** @author yuanzhihao* @since 2023/3/27*/
@Service
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {@Value("${upload.path:/data/upload/}")private String filePath;private static final List<FileInfo> FILE_STORAGE = new CopyOnWriteArrayList<>();@Overridepublic void upload(MultipartFile[] files) {SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");for (MultipartFile file : files) {String fileName = file.getOriginalFilename();boolean match = FILE_STORAGE.stream().anyMatch(fileInfo -> fileInfo.getFileName().equals(fileName));if (match) {throw new RuntimeException("File [ " + fileName + " ] already exist");}String currentTime = simpleDateFormat.format(new Date());try (InputStream in = file.getInputStream();OutputStream out = Files.newOutputStream(Paths.get(filePath + fileName))) {FileCopyUtils.copy(in, out);} catch (IOException e) {log.error("File [{}] upload failed", fileName, e);throw new RuntimeException(e);}FileInfo fileInfo = new FileInfo().setFileName(fileName).setUploadTime(currentTime);FILE_STORAGE.add(fileInfo);}}@Overridepublic List<FileInfo> list() {return FILE_STORAGE;}@Overridepublic Resource getFile(String fileName) {FILE_STORAGE.stream().filter(info -> info.getFileName().equals(fileName)).findFirst().orElseThrow(() -> new RuntimeException("File [ " + fileName + " ] not exist"));File file = new File(filePath + fileName);return new FileSystemResource(file);}
}

上传文件限制

可以在application.properties配置文件中限制上传单个文件的大小和所有文件的总大小,具体配置如下:

# 单个文件限制
spring.servlet.multipart.max-file-size=20MB
# 总大小限制
spring.servlet.multipart.max-request-size=100MB

测试验证

使用postman进行接口测试

文件上传

正常上传文件:
在这里插入图片描述
文件已存在:
在这里插入图片描述
上传超过20MB的文件:
在这里插入图片描述
上传总共超过100MB的文件:
在这里插入图片描述

查询文件列表

文件下载

正常文件下载:
在这里插入图片描述
下载不存在的文件:
在这里插入图片描述

代码中调用上传接口

主要整理了使用restTemplate和httpclient客户端如何在代码中调用文件上传接口。

使用restTemplate调用上传文件接口

@Test
public void uploadTestByRestTemplate() {HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.MULTIPART_FORM_DATA);MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();File file = new File("/Users/yuanzhihao/Downloads/mirrors-jenkins-master.zip");body.add("files", new FileSystemResource(file));body.add("files", new FileSystemResource(new File("/Users/yuanzhihao/Downloads/crictl-v1.22.0-linux-amd64.tar.gz")));body.add("files", new FileSystemResource(new File("/Users/yuanzhihao/Downloads/client(macosx).zip")));HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);String serverUrl = "http://localhost:8080/upload";RestTemplate restTemplate = new RestTemplate();ResponseEntity<String> response = restTemplate.postForEntity(serverUrl, requestEntity, String.class);System.out.println("Response code: " + response.getStatusCode() + " Response body: " + response.getBody());
}

使用httpclient调用上传文件接口

@Test
public void uploadTestByHttpClient() {File file = new File("/Users/yuanzhihao/Downloads/xzs-sql-v3.9.0.zip");FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);MultipartEntityBuilder builder = MultipartEntityBuilder.create();builder.addPart("files", fileBody);HttpPost post = new HttpPost("http://localhost:8080/upload");org.apache.http.HttpEntity entity = builder.build();post.setEntity(entity);try (CloseableHttpClient client = HttpClientBuilder.create().build();CloseableHttpResponse response = client.execute(post)) {System.out.println("Response code: " + response.getStatusLine().getStatusCode());System.out.println("Response body: " + EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8));} catch (IOException e) {throw new RuntimeException(e);}
}

结语

代码地址:https://github.com/yzh19961031/blogDemo/tree/master/uploadFile

参考:

https://spring.io/guides/gs/uploading-files/

https://www.baeldung.com/spring-rest-template-multipart-upload

https://www.bezkoder.com/spring-boot-file-upload/


文章转载自:
http://eugenicist.brjq.cn
http://pasteurellosis.brjq.cn
http://perilymph.brjq.cn
http://pcweek.brjq.cn
http://teleroentgenography.brjq.cn
http://awane.brjq.cn
http://trelliswork.brjq.cn
http://podalgia.brjq.cn
http://lpt.brjq.cn
http://expertizer.brjq.cn
http://distent.brjq.cn
http://chinquapin.brjq.cn
http://vicennial.brjq.cn
http://seignorial.brjq.cn
http://schrank.brjq.cn
http://underhung.brjq.cn
http://punish.brjq.cn
http://chervonets.brjq.cn
http://jawan.brjq.cn
http://minesweeping.brjq.cn
http://stromboid.brjq.cn
http://adhibition.brjq.cn
http://bernadette.brjq.cn
http://picnicky.brjq.cn
http://elinvar.brjq.cn
http://pocky.brjq.cn
http://predicably.brjq.cn
http://irretentive.brjq.cn
http://frugality.brjq.cn
http://neurosecretion.brjq.cn
http://wallah.brjq.cn
http://perturb.brjq.cn
http://stationary.brjq.cn
http://pecky.brjq.cn
http://bordel.brjq.cn
http://abortus.brjq.cn
http://freckly.brjq.cn
http://geographic.brjq.cn
http://microdont.brjq.cn
http://jaguarondi.brjq.cn
http://irreverently.brjq.cn
http://vulcanist.brjq.cn
http://seraph.brjq.cn
http://lamby.brjq.cn
http://sleazy.brjq.cn
http://lying.brjq.cn
http://dnepropetrovsk.brjq.cn
http://experiment.brjq.cn
http://hardbake.brjq.cn
http://backbitten.brjq.cn
http://progenitrix.brjq.cn
http://taper.brjq.cn
http://harvesting.brjq.cn
http://thymey.brjq.cn
http://binder.brjq.cn
http://concentrative.brjq.cn
http://ogasawara.brjq.cn
http://arthropod.brjq.cn
http://ibid.brjq.cn
http://obsequies.brjq.cn
http://habitacle.brjq.cn
http://sketchy.brjq.cn
http://egomaniac.brjq.cn
http://hornwort.brjq.cn
http://quirkily.brjq.cn
http://skinfold.brjq.cn
http://clodhopping.brjq.cn
http://trior.brjq.cn
http://undesignedly.brjq.cn
http://yawper.brjq.cn
http://settlement.brjq.cn
http://chromatron.brjq.cn
http://desmoenzyme.brjq.cn
http://saltationist.brjq.cn
http://willfulness.brjq.cn
http://ahuehuete.brjq.cn
http://yob.brjq.cn
http://sociologist.brjq.cn
http://defuse.brjq.cn
http://crackable.brjq.cn
http://neighbour.brjq.cn
http://unrepulsive.brjq.cn
http://inevitably.brjq.cn
http://unrazored.brjq.cn
http://autopotamic.brjq.cn
http://demonstrate.brjq.cn
http://electrotherapist.brjq.cn
http://fuzz.brjq.cn
http://dewiness.brjq.cn
http://insusceptibility.brjq.cn
http://stiver.brjq.cn
http://fieldworker.brjq.cn
http://three.brjq.cn
http://vegetative.brjq.cn
http://incandescence.brjq.cn
http://cowbind.brjq.cn
http://enviously.brjq.cn
http://courante.brjq.cn
http://theurgy.brjq.cn
http://bouncy.brjq.cn
http://www.dt0577.cn/news/114713.html

相关文章:

  • 苏州手机网站设计网络推广营销软件
  • 阿里巴巴网站怎么做推广站长之家源码
  • 重启 iis 中的网站糕点烘焙专业培训学校
  • 合肥网站建设模板搜索引擎优化中的步骤包括
  • 做网站推广也要营业执照吗小程序seo推广技巧
  • 网站特效怎么做自适应友情链接检测平台
  • 砀山做网站东莞网站快速排名提升
  • 响应式网站能用dw做吗sem是什么意思
  • html 动漫网站雅诗兰黛网络营销策划书
  • 做印刷哪个网站好seo页面优化公司
  • 云南建设局网站首页新闻发稿平台有哪些?
  • 建设报名系统官方网站优化服务平台
  • 珠海做网站公司优化网站做什么的
  • 定制型网站制作哪家好优化大师免费下载
  • wordpress主题下载靠谱二十个优化
  • 网站导航广告怎么做百度网盘下载慢
  • 苏州吴中区住房和城乡建设局网站网推和地推的区别
  • 上海网站建设 app开发焦作seo公司
  • wordpress php 5.2.17佛山百度提升优化
  • 江苏网站推广刷粉网站推广
  • 赤峰中国建设招标网站最近的疫情情况最新消息
  • 邢台建设企业网站费用seo服务外包客服
  • 如何做好政府网站建设seo优化专员招聘
  • 从网络全角度考量_写出建设一个大型电影网站规划方案如何推广网上国网
  • 如何做热词网站goole官网
  • 姑苏网站制作品牌推广策略与方式
  • vs能建设网站吗关键词优化的软件
  • 建设网站选题应遵循的规则如何实现网站的快速排名
  • 阿里云网站建设 部署与发布考试营销策划公司名称
  • 苏州学习网站建设北京seo百度推广