文件上传参考文档:http://blog.didispace.com/spring-cloud-starter-dalston-2-4/

文件下载参考文档:https://blog.csdn.net/aaronsimon/article/details/82710979

我的spring boot ,spring cloud 版本是:

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath/>
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.M9</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

服务调用方 feign文件下载需要配置的config:

import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
public class FeignMultipartSupportConfig {
@Bean
public Encoder feignFormEncoder() {
return new SpringFormEncoder();
}
}  

对应的feign pom.xml需要引入

     <!--feign upload file-->
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form-spring</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>  

服务调用方controller:

import com.yft.common.annotation.Log;
import com.yft.sys.modules.test.fileclient.FileTestClient;
import feign.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import java.io.IOException;
import java.io.InputStream; /**
* feign 熔断器示例
*
* @author oKong
*/
@RestController
@Slf4j
public class FileController { @Autowired
FileTestClient fileTestClient; @Log("文件上传测试")
@PostMapping("/upload")
public Object upload(MultipartFile file) {
log.info("使用feign调用服务,文件上传");
return fileTestClient.upload(file);
} @Log("文件下载测试")
@RequestMapping(value = "/download", method = RequestMethod.GET)
public ResponseEntity<byte[]> downFile() {
log.info("使用feign调用服务 文件下载"); ResponseEntity<byte[]> result = null;
InputStream inputStream = null;
try {
// feign文件下载
Response response = fileTestClient.download();
Response.Body body = response.body();
inputStream = body.asInputStream();
byte[] b = new byte[inputStream.available()];
inputStream.read(b);
HttpHeaders heads = new HttpHeaders();
heads.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=lr.xls");
heads.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); result = new ResponseEntity<byte[]>(b, heads, HttpStatus.OK);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
}

服务调用方feign client写法(文件上传主要是上面第一步配置,文件下载主要是返回的feign 的response):

import com.yft.sys.modules.ClientUrl;
import com.yft.sys.modules.test.fileclient.impl.FileTestClientFallbackFactory;
import feign.Response;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile; /**
* @author lr
*/
@FeignClient(name = ClientUrl.SYSTEM_NAME, fallbackFactory = FileTestClientFallbackFactory.class)
@Component
public interface FileTestClient { /**
* 上传文件测试
*
* @return
*/
@PostMapping(value = ClientUrl.PRE_REQUEST_RUL + "/file/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
Object upload(MultipartFile file); /**
* 下载文件测试
*/
@RequestMapping(value = ClientUrl.PRE_REQUEST_RUL + "/file/download", method = RequestMethod.GET)
Response download(); }

服务调用方 feign client 异常类:

import com.yft.sys.modules.test.fileclient.FileTestClient;
import feign.Response;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile; /**
* @author lr
*/
@Slf4j
@Component
public class FileTestClientFallbackFactory implements FallbackFactory<FileTestClient> {
@Override
public FileTestClient create(Throwable cause) { return new FileTestClient() {
@Override
public Object upload(MultipartFile file) {
log.error("fallback; file upload reason was: " + cause.getMessage());
return null;
} @Override
public Response download() {
log.error("fallback; file download reason was: " + cause.getMessage());
return null;
}
};
}
}

服务提供方呢与原来写法一样,没差别

   @PostMapping(value = "upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public R upload(MultipartFile file) {
try {
String fileName = file.getOriginalFilename();
fileName = FileUtils.renameToUUID(fileName);
String resPath = FileUtils.saveFile(file.getBytes(), filePath, fileName);
// fileService.save(new FileDO() {{
// setCreateDate(new Date());
// setUrl("http://localhost:8004" + filePre + "/"+resPath);
// setType(1);
// }});
return R.ok().put("resPath", resPath);
} catch (IOException e) {
e.printStackTrace();
return R.error("文件上传失败");
}
} @GetMapping("/download")
public void downLoad(HttpServletResponse response) throws IOException {
    //这里示意下载excel文件,自己随便下载点东西
    
/*我们先定义一个嵌套的List,List的元素也是一个List,内层的一个List代表一行数据,
每行都有4个单元格,最终list对象代表多行数据。*/ List<String> row1 = CollUtil.newArrayList("aa", "bb", "cc", "dd");
List<String> row2 = CollUtil.newArrayList("aa1", "bb1", "cc1", "dd1");
List<String> row3 = CollUtil.newArrayList("aa2", "bb2", "cc2", "dd2");
List<String> row4 = CollUtil.newArrayList("aa3", "bb3", "cc3", "dd3");
List<String> row5 = CollUtil.newArrayList("aa4", "bb4", "cc4", "dd4"); List<List<String>> rows = CollUtil.newArrayList(row1, row2, row3, row4, row5);
// 然后我们创建ExcelWriter对象后写出数据: // 通过工具类创建writer,默认创建xls格式
ExcelWriter writer = ExcelUtil.getWriter();
// 一次性写出内容,使用默认样式
writer.write(rows);
//out为OutputStream,需要写出到的目标流 //response为HttpServletResponse对象
response.setContentType("application/vnd.ms-excel;charset=utf-8");
//test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码
response.setHeader("Content-Disposition", "attachment;filename=test.xls");
ServletOutputStream out = response.getOutputStream(); writer.flush(out);
// 关闭writer,释放内存
writer.close(); }

 

文件上传配置yml

#上传文件配置
app:
filePath: D:/uploaded_files/
pre: /files
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Value("${app.filePath}")
String filePath; @Value("${app.pre}")
String pre; @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(pre + "/**").addResourceLocations("file:///" + filePath);
} }

 

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.UUID; public class FileUtils {
public static String saveFile(byte[] file, String filePath, String fileName) {
int random = (int) (Math.random() * 100 + 1);
int random1 = (int) (Math.random() * 100 + 1);
filePath = filePath + random + File.separator + random1 + File.separator;
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(filePath + fileName);
FileChannel fileChannel = fileOutputStream.getChannel();
ByteBuffer buf = ByteBuffer.wrap(file);
while (fileChannel.write(buf) != 0) {
}
} catch (Exception e) { } finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//url
return random + "/" + random1 + "/" + fileName;
} public static boolean deleteFile(String fileName) {
File file = new File(fileName);
// 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
if (file.exists() && file.isFile()) {
if (file.delete()) {
return true;
} else {
return false;
}
} else {
return false;
}
} public static String renameToUUID(String fileName) {
return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
}
}

  

spring cloud feign 文件上传和文件下载的更多相关文章

  1. Spring MVC的文件上传

    1.文件上传 文件上传是项目开发中常用的功能.为了能上传文件,必须将表单的method设置为POST,并将enctype设置为multipart/form-data.只有在这种情况下,浏览器才会把用户 ...

  2. Spring MVC的文件上传和下载

    简介: Spring MVC为文件上传提供了直接的支持,这种支持使用即插即用的MultipartResolver实现的.Spring MVC 使用Apache Commons FileUpload技术 ...

  3. Spring Boot入门——文件上传与下载

    1.在pom.xml文件中添加依赖 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="ht ...

  4. Spring MVC-学习笔记(5)spring MVC的文件上传、下载、拦截器

    1.文件上传.      spring MVC为文件上传提供了直接的支持,这种支持是即插即用的MultipartResolver(多部分解析器)实现的.spring MVC使用Apache Commo ...

  5. Spring +SpringMVC 实现文件上传功能。。。

    要实现Spring +SpringMVC  实现文件上传功能. 第一步:下载 第二步: 新建一个web项目导入Spring 和SpringMVC的jar包(在MyEclipse里有自动生成spring ...

  6. Spring MVC实现文件上传

    基础准备: Spring MVC为文件上传提供了直接支持,这种支持来自于MultipartResolver.Spring使用Jakarta Commons FileUpload技术实现了一个Multi ...

  7. struts2的文件上传和文件下载

    实现使用Struts2文件上传和文件下载: 注意点: (1)对应表单的file1和私有成员变量的名称必须一致 <input type="file" name="fi ...

  8. 【Spring学习笔记-MVC-13】Spring MVC之文件上传

    作者:ssslinppp       1. 摘要 Spring MVC为文件上传提供了最直接的支持,这种支持是通过即插即用的MultipartResolve实现的.Spring使用Jakarta Co ...

  9. spring mvc ajaxfileupload文件上传返回json下载问题

    问题:使用spring mvc ajaxfileupload 文件上传在ie8下会提示json下载问题 解决方案如下: 服务器代码: @RequestMapping(value = "/ad ...

随机推荐

  1. 【SAP业务模式】之STO(二):系统配置

    本篇博文开始讲述STO业务模式的配置! 一.定义发货工厂的装运数据: 目录:SPRO-物料管理-采购-采购订单-设置库存调拨订单-定义工厂的装运数据 定义发货工厂的装运数据: 为收货工厂分配客户代码: ...

  2. 长沙4月21日开发者大会暨.NET社区成立大会活动纪实

    活动总结 2019年4月21日是一个斜风细雨.微风和煦的美好日子,由长沙.NET技术社区.腾讯云云加社区.微软Azure云技术社区.中国.NET技术社区.长沙柳枝行动.长沙互联网活动基地(唐胡子俱乐部 ...

  3. go语言调度器源代码情景分析之五:汇编指令

    本文是<go调度器源代码情景分析>系列 第一章 预备知识的第4小节. 汇编语言是每位后端程序员都应该掌握的一门语言,因为学会了汇编语言,不管是对我们调试程序还是研究与理解计算机底层的一些运 ...

  4. 对SVN的落地与实践总结

    现今最为流行的Git是管理很几套很成熟的分支管理策略.而SVN确实也有,但结合现公司的实际场景还是做了些调整和变动. 一.分支命名规则 所有分支命名采用小写字母 + 数字 + 特殊符号 组成 项目分支 ...

  5. SpringBoot进阶教程(二十五)整合Redis之@Cacheable、@CachePut、@CacheEvict的应用

    在上一篇文章(<SpringBoot(二十四)整合Redis>)中,已经实现了Spring Boot对Redis的整合,既然已经讲到Cache了,今天就介绍介绍缓存注解.各家互联网产品现在 ...

  6. kubernetes实践之五:深入理解Service及内部DNS搭建

    一.Service存在的意义: 防止Pod失联(服务发现) 定义一组Pod的访问策略(负载均衡) 支持ClusterIP,NodePort以及LoadBalancer三种类型 Service的底层实现 ...

  7. hashCode()方法以及集合中Set的一些总结

    一.前言 本篇文章没有什么主题,就是一些零散点的总结.周末没事看了几道蚂蚁金服的面试题,其中有好几道都是特别简单的,基础性的题目,就是我们平时用到的,但是发现要是完全说出来还是有一些不清楚的地方,所以 ...

  8. box-shadow内阴影、外阴影

    外阴影: box-shadow:X轴  Y轴  Rpx  color; 属性说明(顺序依次对应):阴影的X轴(可以使用负值) 阴影的Y轴(可以使用负值) 阴影模糊值(大小) 阴影的颜色 内阴影: bo ...

  9. ArcGIS对SLD样式的支持

    文章版权由作者李晓晖和博客园共有,若转载请于明显处标明出处:http://www.cnblogs.com/naaoveGIS/ 1.ArcGISWMS服务对SLD的支持 在完成用geoserver的w ...

  10. MPP-使用说明

    1.介绍 MPP是瑞芯微提供的媒体处理软件平台,适用于瑞芯微芯片系列.它屏蔽了有关芯片的复杂底层处理,屏蔽了不同芯片的差异,为使用者提供了统一的视频媒体统一接口. 具体提供的功能: 视频编码:H264 ...