在进行开发时,难免会遇到需要上传文件的,如图片音频等到服务器。以下我将会介绍如何上传文件到spring boot中。
过程如下:我们在数据库中建立一张表用来存储路径 ,通过repository获得对数据库的操作方法,在service层完成文件的加载写入,以及保存数据库。
1.我们先建立一个工程:以下先建立一个叫FileUpload的工程,选择对应的依赖。即可创建工程。
工程创建完成后,在目录下创建5个包 controller:控制器 ,entity:数据表对应实体类 ,service:业务逻辑层 ,repository:这里采用的是repository接口对数据库进行操作。
2.在application.properties中添加数据库的相关配置:以下代码连接的是我的本地数据库,相关信息如有不同可做更改。
spring.datasource.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username = root
spring.datasource.password =TS1374206028
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.tomcat.max-active=20
spring.datasource.dbcp2.max-idle=8
spring.datasource.dbcp2.min-idle=8
spring.datasource.dbcp2.initial-size=10
spring.jpa.database = MYSQL
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
3.在entity中创建对应的实体类:(采用@entity注解,可以完成数据表的自建)
实体类中仅包含两个字段:id(设置为自增)和路径
package com.example.demo.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class FilePath {
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPath() {
return Path;
}
public void setPath(String path) {
Path = path;
}
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public Integer id;
public String Path;
}
4.repository层:仅需要创建一个接口,继承crudrepository即可,该接口提供了一些增删改查的方法,可供我们使用
package com.example.demo.repository;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.entity.FilePath;
public interface FilePathRepository extends CrudRepository<FilePath, Integer> {
}
5.接下来就是重点:业务逻辑层,这里实现了文件的写入和数据库路径的写入
首先:我们要理一下如何进行操作: 1.前端会传输一个文件。那么该方法的参数将会是一个文件。2.然后通过io流的方法,将该文件写在对应的文件目录中 3.在文件写入之后,将这个路径连同文件名一起存入数据库中。
具体实现如下:
package com.example.demo.service;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.example.demo.entity.FilePath;
import com.example.demo.repository.FilePathRepository;
import com.example.demo.util.FileUtil;
@Service
public class FilePathService {
@Autowired
private FilePathRepository filePathRepository;
public String Upload(@RequestParam("file") MultipartFile file) {
if(!file.isEmpty()) {
// 获取文件名称,包含后缀
String fileName = file.getOriginalFilename();
// 存放在这个路径下:该路径是该工程目录下的static文件下:(注:该文件可能需要自己创建)
// 放在static下的原因是,存放的是静态文件资源,即通过浏览器输入本地服务器地址,加文件名时是可以访问到的
String path = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/";
try {
// 该方法是对文件写入的封装,在util类中,导入该包即可使用,后面会给出方法
FileUtil.fileupload(file.getBytes(), path, fileName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 接着创建对应的实体类,将以下路径进行添加,然后通过数据库操作方法写入
FilePath biaopath = new FilePath();
biaopath.setPath("http://localhost:8080/"+fileName);
filePathRepository.save(biaopath);
}
return "success";
}
}
6. util工具类中FileUtil类:io流写入文件
package com.example.demo.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileUtil {
//静态方法:三个参数:文件的二进制,文件路径,文件名
//通过该方法将在指定目录下添加指定文件
public static void fileupload(byte[] file,String filePath,String fileName) throws IOException {
//目标目录
File targetfile = new File(filePath);
if(targetfile.exists()) {
targetfile.mkdirs();
}
//二进制流写入
FileOutputStream out = new FileOutputStream(filePath+fileName);
out.write(file);
out.flush();
out.close();
}
}
7.最后是controller:
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.example.demo.service.FilePathService;
@Controller
public class FileUploadController {
@Autowired
private FilePathService filePathService;
// 传入的参数file是我们指定的文件
@RequestMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) {
return filePathService.Upload(file);
}
}
8.最后看一下整体的目录结构:
9.采用postman进行运行测试:可以看到显示成功,
打开static文件夹:能看到上传的文件
打开数据表:能看到该路径(保存的是通过浏览器能够访问的路径)
最后将该路径在浏览器中打开:我们是能够看到该图片的
以上