springcloudfeign⽂件上传和⽂件下载⽂件上传参考⽂档:
⽂件下载参考⽂档:
我的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>
&porting.outputEncoding>UTF-8</porting.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:
dec.Encoder;
import feign.form.spring.SpringFormEncoder;
import t.annotation.Bean;
import t.annotation.Configuration;
@Configuration
public class FeignMultipartSupportConfig {
@Bean
public Encoder feignFormEncoder() {
return new SpringFormEncoder();
}
}
对应的l需要引⼊
<!--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.yftmon.annotation.Log;
import com.st.fileclient.FileTestClient;
import feign.Response;
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()];
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.dules.ClientUrl;
import com.st.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.st.fileclient.FileTestClient;
import feign.Response;
import feign.hystrix.FallbackFactory;
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) {
<("fallback; file upload reason was: " + Message());
return null;
}
@Override
public Response download() {
<("fallback; file download reason was: " + Message());
return null;
}
};
}
}
服务提供⽅呢与原来写法⼀样,没差别
@PostMapping(value = "upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public R upload(MultipartFile file) {
try {
String fileName = OriginalFilename();
fileName = ameToUUID(fileName);
String resPath = FileUtils.Bytes(), filePath, fileName);
// fileService.save(new FileDO() {{
// setCreateDate(new Date());
// setUrl("localhost:8004" + filePre + "/"+resPath);
// setType(1);
// }});
return R.ok().put("resPath", resPath);
} catch (IOException e) {
e.printStackTrace();
("⽂件上传失败");
}
}
@GetMapping("/download")
public void downLoad(HttpServletResponse response) throws IOException {
//这⾥⽰意下载excel⽂件,⾃⼰随便下载点东西
/*我们先定义⼀个嵌套的List,List的元素也是⼀个List,内层的⼀个List代表⼀⾏数据,
每⾏都有4个单元格,最终list对象代表多⾏数据。*/
List<String> row1 = wArrayList("aa", "bb", "cc", "dd");
List<String> row2 = wArrayList("aa1", "bb1", "cc1", "dd1");
List<String> row3 = wArrayList("aa2", "bb2", "cc2", "dd2");
List<String> row4 = wArrayList("aa3", "bb3", "cc3", "dd3");
List<String> row5 = wArrayList("aa4", "bb4", "cc4", "dd4");
List<List<String>> rows = wArrayList(row1, row2, row3, row4, row5);
// 然后我们创建ExcelWriter对象后写出数据:
// 通过⼯具类创建writer,默认创建xls格式
ExcelWriter writer = Writer();
// ⼀次性写出内容,使⽤默认样式
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 = OutputStream();
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 (!ists()) {
targetFile.mkdirs();
}
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(filePath + fileName);
FileChannel fileChannel = Channel();
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 (ists() && file.isFile()) {
if (file.delete()) {
return true;
} else {
return false;
}
} else {
return false;
}
}springcloud和springboot
public static String renameToUUID(String fileName) {
return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1); }
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论