Java微服务RestTemplate跨服务⽂件上传下载
说明:微服务架构使⽤springcloud
需求1:A服务是业务,B服务是功能【⽂件上传】,⽤户通过浏览器上传⽂件file,上传访问A服务,A服务调⽤B服务的上传功能需求2:A服务是业务,B服务是功能【⽂件下载】,⽤户通过浏览器下载⽂件file,下载访问A服务,A服务调⽤B服务的下载功能话不多说,上代码:
A服务【A调⽤B】:
import com.sysmon.Result;
import io.swagger.annotations.*;
slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Objects;
/**
* ⽂件服务
* @author 李庆伟
* @date 2021/8/31 14:53
*/
@Slf4j
@RequestMapping("web/files")
@RestController
@Api(value = "⽂件服务", tags = "⽂件服务")
public class FilesWebController {
@Autowired
private RestTemplate restTemplate;
java下载过程private static final String SERVER_TRILATERAL_9400 = "SERVER-TRILATERAL-9400";
/**
* ⽂件上传
* [id]
* @return {@link Result}
* @throws
* @author 李庆伟手机jsp文件查看器
* @date 2021/7/29 9:56
*/
@PostMapping("upFile")
@ApiOperation(value = "⽂件上传", notes = "⽂件上传", produces = "application/json")h5页面影视源码
@ApiResponses({
@ApiResponse(code = 0, message = "id:⽂件id"),
})//@ApiParam(required = true, value = "上传的⽂件") @RequestParam(value = "file" ,required = true)
public Result upFile(MultipartFile file){
// 封装参数,千万不要替换为Map与HashMap,否则参数⽆法传递
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
paramMap.add("file",Resource());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
//headers.add();在请求头中设置传递信息
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
Result result = restTemplate.postForObject(SERVER_TRILATERAL_9400+"/files/upFile",httpEntity,Result.class);
return result;
}
/**
* 图⽚展⽰[跨服务调⽤]
* [id]
* @return {@link Result}
* @throws
* @author 李庆伟
* @date 2021/9/6 19:15
*/
@GetMapping("downFileCross")
public void downFileCross(@ApiParam(required = true, value = "图⽚id") @RequestParam String id, HttpServletResponse response){ // 封装参数,千万不要替换为Map与HashMap,否则参数⽆法传递
ResponseEntity<byte[]> rsp = ForEntity(SERVER_TRILATERAL_9400+"/files/downFileCross?id="+id,byte[].class); BufferedInputStream bis = null;
if (Null(rsp)) {
byte[] body = Body();
if (Null(body)) {
try {
InputStream is = new ByteArrayInputStream(body);
BufferedImage image = ad(is);
//判断是否是图⽚ 1.是预览 2.下载
if(image!=null){
//打开本地⽂件流
//激活下载操作
response.setContentType("image/jpeg");
ImageIO.write(image, "JPEG", OutputStream());
} else {
log.info("⽂件⼤⼩==>:{}", body.length);
String filename = "李庆伟.jpg";//这⾥应该查询出⽂件名称,为了⽅便就随便命名了
c语言编译环境有哪些response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename=" + new Bytes("utf-8"), "ISO8859-1"));
bis = new BufferedInputStream(is);
OutputStream os = OutputStream();
byte[] buffer = new byte[2048];
int i = ad(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = ad(buffer);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
B服务【被A调⽤】
控制层:
/**
* ⽂件上传
* [file, request]
* @return {@link Result}
* @throws
* @author 李庆伟
* @date 2021/9/4 18:05
*/
imgplay猫咪表情包@PostMapping("upFile")
@ApiOperation(value = "⽂件上传", notes = "⽂件上传", produces = "application/json")
@ApiResponses({
@ApiResponse(code = 0, message = "id:⽂件id"),
})
public Result upFile(@ApiParam(required = true, value = "上传的⽂件") @RequestParam(value = "file" ,required = true) MultipartFile file){
CClientFile cClientFile = fileService.upFile(file);
return Result.success(cClientFile);//返回上传成功⽂件信息
}
/**
* 下载和预览[⽀持跨服务调⽤]
* [id]
* @return {@link Result}
* @throws
* @author 李庆伟
* @date 2021/9/4 20:15
*/
@GetMapping("downFileCross")
@ApiOperation(value = "⽂件下载[⽀持跨服务调⽤]", notes = "⽂件下载[⽀持跨服务调⽤]", produces = "application/json")
public ResponseEntity<byte[]> downFileCross(@ApiParam(required = true, value = "⽂件id") @RequestParam(value = "id" ,required = true) String id){ return fileService.downFileCross(id);//返回上传成功⽂件信息
}
实现类:
/**
* ⽂件上传业务
* @return {@link String}
* @throws
* @author 李庆伟
* @date 2021/9/4 19:23
*/
@Transactional
public CClientFile upFile(MultipartFile file) {
CClientFile cClientFile = FileUtil.upFile(file);
if(cClientFile == null){
throw new MyException(2001,"⽂件为空⽂件");
}
String id = IdWorker.makeIdWorker();
cClientFile.setId(id);
cClientFile.setCreateDate(new Date());
fileMapper.insert(cClientFile);
return cClientFile;
}
* ⽂件下载[⽀持微服务]
* [id]
* @return {@link ResponseEntity<byte[]>}
* @throws
* @author 李庆伟
* @date 2021/9/7 16:40
*/
public ResponseEntity<byte[]> downFileCross(String id) { CClientFile cClientFile = fileMapper.selectById(id);
if(cClientFile != null){
return FileUtil.downFileCross(cClientFile);
}
return null;
}
⼯具类:
import del.CClientFile;
slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
/**
* @author 李庆伟
* @date 2021/9/4 18:08
*/
@Slf4j
public class FileUtil {
private static final String rootUtl = Property("os.name").toLowerCase().startsWith("win")?"D:/file_db/":"/file_db/";
/**
* ⽂件上传
精子分级直方图怎么看* [file]
* @return {@link String}
* @throws
* @author 李庆伟
* @date 2021/9/4 18:15
*/
public static CClientFile upFile(MultipartFile file){
CClientFile cClientFile = new CClientFile();
//如果⽂件不为空
if (!file.isEmpty()) {
String oldFileName = OriginalFilename();
String realPath = rootUtl + new SimpleDateFormat("yyyy/MM/dd/hh/mm/ss").format(new Date())+"/"+ UUID.randomUUID().toString().replaceAll("-", "");
File f = new File(realPath);
if(!f.exists()){
f.mkdirs();//如果⽬录不存在,创建⽬录
}
try {
//可以在这完成数据库路径的存储
} catch (Exception e) {
e.printStackTrace();
}
cClientFile.setFileName(oldFileName);//封装⽂件名称
cClientFile.setFileUrl(realPath + "/" + oldFileName);//封装⽂件路径
cClientFile.Size());//封装⽂件⼤⼩
return cClientFile;//返回到成功页⾯
}else {
return null;//返回到失败的页⾯
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论