当前位置:网站首页>Practice of online problem feedback module (11): realize image download function
Practice of online problem feedback module (11): realize image download function
2022-07-23 10:15:00 【Bug bacteria ¹】
author :bug bacteria
official account : Ape circle wonderful house
important clause : Originality is not easy. , For reprint, please attach the original source link and this statement , Thank you for your cooperation .
Copyright notice : Some words or pictures in the article may come from the Internet or Baidu Encyclopedia , If there is infringement, please contact bug Bacterial treatment .
One 、 Preface
The next few issues ,bug I want to share with you that I just received a temporary demand yesterday , It's hot , I would like to share how I faced the temporary requirements and made the whole development cycle , It includes sorting out businesses, creating business tables, realizing business logic to form a closed loop, and connecting with the front end , Some business development and functional development will be interspersed , This one-stop process is witnessed online with you , Share with the novice , I hope it will help you .
Environmental statement :idea2019.3 + springboot2.3.1.REALSE + mybati-plus3.2.0 + mysql5.6 + jdk1.8
If the partners feel that the article is helpful to you in the process of reviewing the article , Please don't be stingy with your praise , Boldly put the article Lighten up Well , Your likes are three in a row ( Collection ️+ Focus on + Leaving a message. ) That's right bug The best encouragement and support on my creative path . Time does not give up *️, Create constantly , come on. ️
Two 、 Text
This issue , I then focus on the picture , Since we want to teach , It is necessary to complete the addition, deletion, modification and check of the pictures . So for you in the future , If there is any business related to pictures , Then you have no pressure , Follow my tutorial directly , I'll teach you hand in hand , This must be the fastest and best zero foundation introductory teaching , Maybe they will be appreciated by the leaders , Work , It's not just about code safety and efficiency , Get off work early , Try to finish the workload of the day within working hours , This is the goal of everyone , It's yours and mine .
Let's not talk more nonsense , Start today's content directly .
3、 ... and 、 How to code image download
Our content today is to download pictures , Since the business supports image uploading , Then you must support local downloading of images , So how to download images from the server to the local ? This is obviously a problem ? But today I , From zero to zero, I will lead you to complete analysis, implementation, and testing , One stop service to arrange you all properly .
1️⃣ Definition Controller request
Let's define the interface request first , So let's analyze that , Since the picture is to be downloaded , You must find the full path of the image , So for this business interface , The input parameter definitely needs two parameters , Enter the reference 1 The full name of the picture , for example test.jpg, Enter the reference 2 Domain account id, Because if you want to splice the full path of the image resource address , This must be based on the domain account id To be spliced as sub paths , This is also related to the business definition , You can also not distinguish people , Just put all the picture resources in a large resource pool , I just need to upload people into folders , To need someone to upload the saved domain account id As a precondition .
Now that the analysis is finished, enter the parameters , Then the interface definition will have an outline , Let's see . For reference only :
@GetMapping("/download-img-by-path")
@ApiOperation(value = " Images are downloaded ", notes = " Download pictures according to the picture address ")
public void downloadImgByPath(@ApiParam(" Picture path ") @RequestParam("imgPath") String imgPath,
@ApiParam(" Domain account number of the feedback person id") @RequestParam("accountId") String accountId) throws IOException {
userQuestionsService.downloadImgByPath(imgPath, accountId);
}It should be noted that , Your interface request path , It's best to know what you mean by what you see , It is also convenient to debug and distinguish interface requests on the page in the future .
2️⃣ Definition downloadImgByPath() Interface
Then we're going to service The interface layer defines the downloadImgByPath() The method .
void downloadImgByPath(String imgPath, String accountId) throws IOException;3️⃣ Realization downloadImgByPath() Method
Next is the core of the interface , But here , In order to avoid code redundancy in the future , Here we still encapsulate the image download method into a public method , So for some pictures to download ,pdf Download and other files , Just call it directly , Let's package , The most important thing is the resource saving path , therefore , If you want to join us, just give us a break , Download resources according to the resource path .
The specific code implementation is as follows :
@Override
public void downloadImgByPath(String imgPath, String accountId) throws IOException {
// Full path of stitching preview picture
String targetPath = this.buildImgPath(imgPath, accountId);
// Call the download method
uploader.downloadImg(targetPath);
}For the image path splicing method , It depends on your actual business , Just splice all the saved paths of the resource . Then I also encapsulated the core method of the image into uploader It's in the actuator , It involves public methods such as uploading and downloading resources .
4️⃣ Realize the picture downloadImg() Download method
How to download image resources , This requires the help of a tool ,IOUtils Tool class , It has a method that provides a stream assignment copyLarge(), You can look at its source code , Interested friends can think about it .
public static long copyLarge(InputStream input, OutputStream output) throws IOException {
return copy(input, output, 4096);
}and copyLarge() Method is also an important step to download image resources , How to use it in combination , Please have a look at bug The core method of bacteria writing , For reference only .
/**
* Images are downloaded
*/
public void downloadImg(String targetPath) {
FileInputStream inputStream = null;
HttpServletResponse response = SpringServletContextUtils.getResponse();
try {
// Set file header , The last parameter is to set the download file name
response.setHeader("Content-Disposition", "attachment;fileName=" + FilenameUtils.getName(targetPath));
File file = new File(targetPath);
inputStream = new FileInputStream(file);
OutputStream outputStream = response.getOutputStream();
IOUtils.copyLarge(inputStream, outputStream);
outputStream.flush();
} catch (IOException e) {
log.error(e.getMessage(), e);
} finally {
// Shut off flow
IOUtils.closeQuietly(inputStream);
}
}This method is very brief , The only thing to be exposed is the full path of resources , This has to be determined by the caller , If the resource does not exist , It must fail to download .
5️⃣ The interface test
Then we will test the image download , This also involves a very important link , If you are an interface not added to the white list , That must involve token Login authentication , So for safety's sake , I set the interface call to not block the whitelist , That is, I can directly request the address through the browser to download the image resources .
Or you can use postman Interface debugging , It also supports the image download function , I will demonstrate it to you below .
Mode one : Browser test image download

First of all, you should ensure that the image resource exists , So here I am , I am making sure that the picture exists , Let me show you .

You must ensure that you can find resources for the full path of the picture , Otherwise, it must be a blank picture . As shown in the figure below :

And the correct address , Download the picture , open , To be exact, it must be the picture you specified to download .

Mode two :postman Test image download
choice send You can preview the picture directly , But what we want is to save the image from the server to the local , That is, we pull down 【Send】 choice 【Send and download】 Option will jump to open a locally saved window , I will choose to save to the desktop .

I saved it directly to the desktop , You can see that , The default file name will be changed to response, It is not downloaded and saved according to its original name, but downloading through the browser will not cause such problems .

6️⃣ summary
Relatively speaking , It's still one step , Nothing happened bug, This measurement function is available , You can rest assured copy Ha .
... ...
All right. , The above is all about this issue , Have you learned to give up ? If it helps you , Please don't forget to give bug bacteria [ Three companies support ] yo . If you want to get more learning resources or want to communicate with more technology enthusiasts , You can pay attention to my official account. 『 Ape circle wonderful house 』, The backstage replies the key words to get the learning materials 、 Big factory surface 、 Interview templates and other massive resources , Just wait for you to get .
Four 、 I recommend
For the actual development of the problem feedback module , I combed the teaching and link address of each issue completely , For reference only : I hope it can help you .
- Practice of online problem feedback module ( One ): Sort out business requirements and create database tables
- Practice of online problem feedback module ( Two ): Encapsulate code to automatically generate class file
- Practice of online problem feedback module ( 3、 ... and ): Automatically generate all Controller、Service、Mapper Wait for the documents
- Practice of online problem feedback module ( Four ): Encapsulate generic field classes
- Practice of online problem feedback module ( 5、 ... and ): Realize the automatic filling function of general field content
- Practice of online problem feedback module ( 6、 ... and ): Interface document definition
- Practice of online problem feedback module ( 7、 ... and ): Installation and deployment swagger2
- Practice of online problem feedback module ( 8、 ... and ): Realize image upload function ( On )
- Practice of online problem feedback module ( Nine ): Realize image upload function ( Next )
- Practice of online problem feedback module ( Ten ): Realize the picture preview function
- Practice of online problem feedback module ( 11、 ... and ): Realize the picture download function
- Practice of online problem feedback module ( Twelve ): Realize the function of deleting pictures
- Practice of online problem feedback module ( 13、 ... and ): Realize multi parameter paging query list
- Practice of online problem feedback module ( fourteen ): Realize the online question answering function
- Practice of online problem feedback module ( 15、 ... and ): Realize the function of online updating feedback status
- Practice of online problem feedback module ( sixteen ): Realize the function of checking details
- Practice of online problem feedback module ( seventeen ): Realization excel Template online download function
- Practice of online problem feedback module ( eighteen ): Realization excel Batch import function of account file records
- Practice of online problem feedback module ( nineteen ): Realize batch export of data to excel Function in file
- Practice of online problem feedback module ( twenty ): Conclusion
The above is the content of 20 issues , Each issue is dry , For the development of a module , How to build and test the deployment online bit by bit , I'll say it again , This is not an exercise , It's actual combat ! It's actual combat ! It's actual combat !
If you think you just need to understand one of the knowledge points or business , No objection , Just choose a few of them to study , It's all over anyway ; I just hope you can gain something , Grow up , It's not in vain for me to summarize and update you after work every day .
5、 ... and 、 At the end of the article
If you want to learn more , Little friends can pay attention to bug I created a special column for you 《springboot Zero basic introductory teaching 》, It's all my hands , Ongoing update , I hope I can help more friends .
I am a bug bacteria , A procedural ape who wants to get out of the mountain and change his fate . There's a long way to go , Are waiting for us to break through 、 To challenge . Come on , friends , Let's cheer together ! The future can be expected ,fighting!
Finally, I'll give you two words I like very much , Share with you !
️ Be what you want to be , No time limit , As long as willing , Anytime? start.
You can change... From now on , It can be the same , This matter , There are no rules , You can live your best .
If the article helps you , Just leave your Fabulous Well !(#^.^#);
If you like bug Sharing articles , Just... Please bug Bacteria point Focus on Well !(๑′ᴗ‵๑)づ╭~;
If you have any questions about the article , Please also at the end of the text Leaving a message. perhaps Add group Well 【QQ Communication group :708072830】;
Given the limited personal experience , All viewpoints and technical research points , If there is any objection , Please reply directly to participate in the discussion ( Do not make offensive remarks , thank you );
Copyright notice : Originality is not easy. , For reprint, please attach the original source link and this statement , copyright , Piracy must be investigated !!! thank you .
边栏推荐
猜你喜欢

新的项目实现的技术点如有需要可以指导

数组中的逆序对

A concise tutorial for soft exam system architecture designer | reverse engineering
![[300 + selected interview questions from big companies continued to share] big data operation and maintenance sharp knife interview question column (VII)](/img/cf/44b3983dd5d5f7b92d90d918215908.png)
[300 + selected interview questions from big companies continued to share] big data operation and maintenance sharp knife interview question column (VII)

Decompile the jar package / class file / modify the jar package using the decompile plug-in of idea

Technology sharing | big transaction blocking show master status

C语言文件操作

枚举类的使用和实现

C语言柔性数组

STM32 - input capture experiment
随机推荐
C语言柔性数组
30行自己写并发工具类(Semaphore, CyclicBarrier, CountDownLatch)是什么体验?
目标检测xml文件实现mixup数据增强(修改文件路径直接能用,非常方便)
Error msb4181: the "qtrunwork" task returned false, but no error was recorded
Use reflection to modify the member variable whose modifier is final
【Azure 事件中心】Azure Event Hub 新功能尝试 -- 异地灾难恢复 (Geo-Disaster Recovery)
如何在OneFlow中新增算子
ssm框架外卖订餐系统
多线程中的「lost wake up 问题」| 为什么wait()和notify()需要搭配synchonized关键字使用?
实现城市治理一网统管,必须这 4 个关键技术
三数之和:(排序+双指针+剪枝)
How to do the system security test? Let's talk about it in detail
十年磨一剑,云原生分布式数据库PolarDB-X的核心技术演化
Ten years of sharpening a sword, the core technology evolution of the cloud native distributed database polardb-x
使用IDEA的反编译插件 反编译jar包/class文件/修改jar包
Time series dataset: power transformer dataset (etdataset)
redis分片集群如何搭建与使用
Transfer software testing salary 10K | there is food in the hand and a bottom in the heart, which is the truth at all times
redis token记录用户登录设计求解?
How to classify the same field values in a list under the same list
