Make writing a habit together! This is the 15th day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.
Feign upload and download
The problem background
Based on some mainstream frameworks at present, microservice architecture is basically used. In many cases, the function of file file management will be extracted to an independent microservice such as File microservice.
Front-end request, all unified call file micro service file upload and download function!!
Such a design, as if there is no problem, unified management!!
Due to file upload, business data may also need to be written, such as attachment information, which has to be extracted into an independent micro-service for the front-end to use.
That will have a problem ah:!! T_T
1. What if my attachments aren’t uploaded through the front end? I am a backend server and need to save an attachment.
2. One of my back-end services needs to read A file and parse it. Because of the distributed architecture, the file microservice may be deployed to server A, but the back-end service may be deployed to service B, so the file cannot be read according to the disk path.
Yes, yes, what you said is very reasonable, this is really a big problem!!
Don’t panic, we will solve this problem today!!
Because our calls to interfaces between services, in microservices, are generally invoked through Feign. Can we also call the file through feign?
The answer must be yes, ha ha!! ^_^
That nonsense don’t say much, top code!!
The Feign interface is ready
- To define a
Feign
Upload, download interface
@FeignClient(name = "file", Configuration = {vicinity MultipartSupportConfig. Class}) public interface FileClient {/ * * * * @ param you upload the file * @return */ @RequestMapping(path = "/file/upload", consumes = {"multipart/form-data"}) JsonResult upload(@RequestPart(name="file") MultipartFile file); /** * Download file */ @getMapping (path = "/file/download/{fileId}") Response Download (@pathVariable (name = "fileId") String fileId); public class MultipartSupportConfig { @Bean @Primary @Scope("prototype") public Encoder feignFormEncoder() { return new SpringFormEncoder(); }}}Copy the code
The file micro service
Provide the documentsupload
interface
@RequestMapping("/file/upload") public JsonResult upload(MultipartHttpServletRequest request) throws Exception { JsonResult jsonResult = new JsonResult(); String timestamp = request.getParameter("time"); MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap(); List<MultipartFile> files = multiFileMap.get("files"); if (BeanUtil.isEmpty(files)) { files = multiFileMap.get("file"); } Iterator<MultipartFile> it = files.iterator(); while (it.hasNext()) { MultipartFile multipartFile = it.next(); TransferTo (new File(" File path ")); // Save to disk multipartfile.transferto (new File(" File path ")); // Record file upload service data... xxxxFileDao.saveFile(xxxFile); } jsonResult.setSuccess(true); jsonResult.setData(fileList); Jsonresult. setMessage(" Upload successful!" ); return jsonResult; }Copy the code
The file micro service
Provide the documentsdownload
interface
@GetMapping("/download/{fileId}") public void feigndownloadOne(@PathVariable("fileId") String fileId, HttpServletResponse Response) throws Exception {// Find files by fileId... xxxFile = xxxxFileDao.getFile(fileId); File File = new File(" File path "); String filename = xxxFile.getName(); String type ="attachment"; response.setHeader("Content-Disposition", type + "; filename=" + filename); FileInputStream fis = new FileInputStream(file); BufferedInputStream buff = null; OutputStream out = null; try { buff = new BufferedInputStream(fis); out = response.getOutputStream(); IOUtils.copy(buff, out); } finally { out.flush(); Fis.close (); fis.close(); buff.close(); }}Copy the code
When downloading this interface, it is important to not close() the out stream, otherwise the business logic will not be processed if the stream is retrieved.
The feign interface and the file microservice upload and download interface have been defined.
Upload and download interface, just give a demo, big guy, can modify, the corresponding business logic!! ^_^
Feign upload and download
Next, we will use the upload and download function of Feign!!
- upload
Feign interface
, the use of
import java.io.File;
import java.io.FileInputStream;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.mock.web.MockMultipartFile;
import org.apache.http.entity.ContentType;
File pdfFile = new File("D://test.pdf");
FileInputStream fileInputStream = new FileInputStream(pdfFile);
MultipartFile multipartFile = new MockMultipartFile(pdfFile.getName(), pdfFile.getName(),
ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
/ / upload
JsonResult jsonResult = fileClient.upload(multipartFile);
if (jsonResult.isSuccess() && jsonResult.getCode() == 200) {}Copy the code
Pay attention, pay attention!! !
The upload interface receives files with a MultipartFile object, so we need to convert the File object to a MultipartFile object before we can call this interface.
Conversion mode, see the above code!!
Ok, this is the example of uploading files, is relatively simple!!
- download
Feign interface
, the use of
import feign.Response; // File stream Response Response = fileclient.download (fileId); InputStream in = null; if(response.status() == 200){ Response.Body body = response.body(); in = body.asInputStream(); // Get the in stream, process the corresponding business logic... After processing, remember to close the inputStream if(in! = null){ in.close(); }}Copy the code
Pay attention, pay attention!! !
There are two things to note here:
1. For the download interface, the out stream has not been closed () yet, so the in stream should be used up by close().
2. The code here, in the development process, can not break point debugging, can not break point debugging, can not break point debugging!!
3 important things to say, do not break the debugging point, because after you break the debugging point, the in stream, because the toString() method is executed, the in stream will be closed, that is, can not handle the business logic code!!
Ok, this is the example of uploading files, is relatively simple!!
Ok, Feign upload and download, roughly implemented, that’s it!! ^_^
Then we can have fun writing code!! ^_^