这周培训中有一天的作业是使用SpringBoot实现文件上传功能,老师的要求是在他搭好的基础上加上文件上传模块和前端上传的部分,spring工程搭好了,老师写的代码比较多,虽然实现了功能,但是不助于对工程以及springboot机制的理解,去b站搜了某大佬up主的课程就自己亲自实现一下~
主要任务:搭建springboot工程,使用postman进行测试,从前端上传一个文件,上传到后端,并进行存储。
注意:请准备IDEA和postman进行测试
工程的结构如下:
分析: 工程包括service层、entity层、controller层和TestApplication
其中controller层对request进行response,即接受指定的请求
entity层对于消息进行封装,对于本工程,由于需要对文件上传状态进行反馈,我们定义code、message、body用来表示状态码(200,500,400等)message表示服务器端传的消息,body表示主体
service层对文件进行处理,主要是文件上传功能upload()的接口和其实现
TestApplication则是springboot运行的调用入口
首先创建一个项目,
notice:选择default会创建不了,可以把https://start.spring.io复制到custom一行,选择custom即可next,
实在不行,就去创建maven空工程,自己导入pom.xml依赖吧
自己命名,这里命名为file.upload,别的都不变(按照你自己的版本)
这里可以选择所需要的依赖,我们只需一个spring web即可,然后再next-finish即可
这时候你的工程就自动创建了,但是idea提示你导入maven的包,按下fix和enable auto import即可
可以看到,此时项目中没有报错,只有以下目录结构(其实是只有UploadApplication.class)
我们首先在file.upload创建controller、entity、service三个层的目录
在entity下创建消息处理实体类(泛型)Resp<E>,包括以下三个字段
private String message;
private String code;
private E body;
以及右键生成他们的getter and setter
再到最后处理正确和失败的函数,对于成功,返回200,对于失败,返回http失败的状态码等信息
public static <E> Resp<E> Succeed(E body){return new Resp<E>("200","",body);}public static <E> Resp<E> Failed(String code,String message){return new Resp<E>(code,message, null);}
再在service层下创建接口 IUpload,用来处理upload的函数接口
Resp<String> upload(MultipartFile file);
再在service层创建子文件夹,名为impl,用来对刚写的接口进行实现
在实现的public Resp<String> upload(MultipartFile file)函数中,编写对文件处理的代码即可
@Overridepublic Resp<String> upload(MultipartFile file) {if(file.isEmpty()){return Resp.Failed("400","File Not Exists");}String ori_name=file.getOriginalFilename();String cur_name=System.currentTimeMillis()+"."+ori_name.substring(ori_name.lastIndexOf(".")+1);String path="D://TmpFile";File curr_file =new File(path+cur_name);if(!curr_file.getParentFile().exists()){curr_file.getParentFile().mkdirs();}try{file.transferTo(curr_file);}catch(IOException e){e.printStackTrace();return Resp.Failed("500","Error");}return Resp.Succeed("200");}
再在controller文件夹下创建Controller类
@org.springframework.stereotype.Controllerpublic class Controller {@AutoWiredIUpload ip;@RequestMapping(value = "/upload",method = RequestMethod.POST)public Resp<String> uploadfile(@RequestParam("file") MultipartFile file){return ip.upload(file);}}
可以在application.properties对配置信息进行更改
我改了端口号(你可以不改,使用默认端口8080)
server.port=8787
然后就可以运行了,运行UploadApplication即可
打开postman进行测试
先输入URLlocalhost:8787/upload,选择post类型
在key中选择File类型,并输入file,value中上传文件即可send
此时返回了信息200,表示文件上传成功!
此时打开硬盘,文件也显示出来了!!Congratulations!!!
注意:Springboot的那些注解配置,例如@Service @AutoWired @Controller @RequestMapping
一定要写上去,漏掉一个的话springboot找不到 就会报java.null.pointer.exception的错误
以下是所有代码
Controller.class:
package file.upload.controller;import file.upload.entity.Resp;import file.upload.service.IUpload;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.multipart.MultipartFile;@RestControllerpublic class Controller {@AutowiredIUpload ip;@RequestMapping(value = "/upload",method = RequestMethod.POST)public Resp<String> uploadfile(@RequestParam("file") MultipartFile file){return ip.upload(file);}}
uploadimpl.class的代码
package file.upload.service.impl;import file.upload.entity.Resp;import file.upload.service.IUpload;import org.springframework.stereotype.Service;import org.springframework.web.multipart.MultipartFile;import java.io.File;import java.io.IOException;@Servicepublic class Uploadimpl implements IUpload {@Overridepublic Resp<String> upload(MultipartFile file) {if(file.isEmpty()){return Resp.Failed("400","File Not Exists");}String ori_name=file.getOriginalFilename();String cur_name=System.currentTimeMillis()+"."+ori_name.substring(ori_name.lastIndexOf(".")+1);String path="D:\\TmpFile\\";File curr_file =new File(path+cur_name);if(!curr_file.getParentFile().exists()){curr_file.getParentFile().mkdirs();}try{file.transferTo(curr_file);}catch(IOException e){e.printStackTrace();return Resp.Failed("500","Error");}return Resp.Succeed("200");}}
IUpload.class的代码
package file.upload.service;import file.upload.entity.Resp;import org.springframework.web.multipart.MultipartFile;public interface IUpload {Resp<String> upload(MultipartFile file);}
Good Luck