spring cloud feign 文件上传和文件下载
程序员文章站
2022-04-20 21:10:49
文件上传参考文档:http://blog.didispace.com/spring-cloud-starter-dalston-2-4/ 文件下载参考文档:https://blog.csdn.net/aaronsimon/article/details/82710979 我的spring boot ......
文件上传参考文档:
文件下载参考文档:
我的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);
}
}
上一篇: Java8之Optional类