步骤一:
准备数据库
CREATE TABLE `company` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`company_name` varchar(255) DEFAULT NULL COMMENT '企业名称',
`business_license_url` varchar(255) DEFAULT NULL COMMENT '营业执照上传url'
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=utf8mb4 COMMENT='公司';
步骤二
准备实体类
@Data
public class Company {
private int id;
/**
* 企业名称
*/
private String companyName;
/**
*营业执照上传url
*/
private String businessLicenseUrl;
}
步骤三
配置图片路径
#uploadPathImg=D\:\\img\\ #本地路径 uploadPathImg=/home/uploadedImg/ #服务器路径
步骤四
读取配置文件中的图片路径
@Configuration
@EnableWebMvc
public class MyWebMvcConfiguration implements WebMvcConfigurer {
@Value("${uploadPathImg}")
private String uploadPathImg;
//配置本地文件映射到url上
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//重写方法
//修改tomcat 虚拟映射
registry.addResourceHandler("/uploadeview/**")
.addResourceLocations("file:"+uploadPathImg);//定义图片存放路径
}
}
步骤四
上传图片请求
@RestController
public class test(){
@Value("${uploadPathImg}")
private String uploadPathImg;
@PostMapping("/upload")
public Object upload(@RequestParam(value = "file")MultipartFile file, HttpServletRequest req, Company company) throws IOException {
try {
if (file != null) {
String fileName = System.currentTimeMillis() + file.getOriginalFilename();
String upload_file_dir=uploadPathImg;//注意这里需要添加目录信息
String destFileName = uploadPathImg +fileName;
//4.第一次运行的时候,这个文件所在的目录往往是不存在的,这里需要创建一下目录(创建到了webapp下uploaded文件夹下)
File upload_file_dir_file = new File(upload_file_dir);
if (!upload_file_dir_file.exists())
{
upload_file_dir_file.mkdirs();
}
//5.把浏览器上传的文件复制到希望的位置
File targetFile = new File(upload_file_dir_file, fileName);
file.transferTo(targetFile);
company.setBusinessLicenseUrl(fileName);
}
companyMapper.addCompay(company);
}catch (Exception e){
e.printStackTrace();
}
return company;
}
}
步骤五
添加图片到数据库,数据库中只存图片的名字
写接口
void addCompay(Company company);
接口的实现
<insert id="addCompay" parameterType="com.demo.entity..Compay" useGeneratedKeys="true" keyProperty="id" >
insert into tenant
(
company_name,
business_license_url
)
values
(
#{companyName},
#{businessLicenseUrl}
)
</insert>
测试结果
在浏览器中 访问http://服务器ip地址/uploadeview/16126930576451612677236147shixun_1.png 即可显示图片