阅读量:0
目录
1、文件上传本地
1.1 原理
1.2 如何使用文件上传
1.2.1 引入文件上传的依赖
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.10.RELEASE</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.24</version> </dependency> <!--servlet依赖--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!--jackson依赖:把controller层方法返回的java对象转化为json字符串--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.3</version> </dependency> <!--文件上传依赖--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> </dependencies>
1.2.2 配置文件上传拦截器
<!--文件上传解析器 id:必须为multipartResolver--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--设置文件上传的大小 单位为byte字节 1M=1024kb=1024b 10*1024*1024--> <property name="maxUploadSize" value="10485760"/> <!--设置编码--> <property name="defaultEncoding" value="utf-8"/> </bean>
1.2.3 完成文件上传的代码
<%--表单: 提交方式必须为post enctype编码:multipart/form-data文件编码--%> <form method="post" action="/upload" enctype="multipart/form-data"> <%--input必须设置文件文件框 而且必须起名称--%> 选择上传的文件:<input type="file" name="myfile"/><br> <input type="submit" value="上传"/> </form>
@Controller public class UploadController { /** * * @param myfile 接受你上传的文件对象信息封装到该类。该类中可以获取上传文件的信息。比如:文件名 文件大小 文件后缀等 * 这个名称必须为文件上传表单的文件框的名称一致 * @return */ @PostMapping("/upload") public String upload(MultipartFile myfile, HttpServletRequest request) throws IOException { //获取tomcat上下文中的指定目录的路径 String realPath = request.getSession().getServletContext().getRealPath("/upload"); //根据上面的路径创建一个文件对象 File file=new File(realPath); //如果没有该目录则创建 if (!file.exists()) { file.mkdirs(); } //把上传的文件转移到upload目录下--重名覆盖了 String uuid = UUID.randomUUID().toString().replace("-", ""); File target=new File(realPath+"/"+(uuid+myfile.getOriginalFilename())); myfile.transferTo(target); return "success"; } }
2、文件上传oss服务器
2.1 为什么需要上传到oss服务器
如果项目搭建了集群。那么导致文件数据无法共享。
如果项目的target删除了。导致文件数据丢失。
2.2 如何使用oss
2.2.1 开启oss服务
点击上面链接,跳转到阿里云的oss服务器页面,完成登录后,会进入oss管理控制台,如图所示
然后点击创建Bucket,操作如下图
2.2.2 在Java中引入依赖
<dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.15.1</version> </dependency>
2.2.3 查看自己ID和密钥
2.2.4 代码
@PostMapping("/upload2") public String upload2(MultipartFile myfile){ // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。 String endpoint = "oss-cn-beijing.aliyuncs.com"; // 填写Bucket名称,例如examplebucket。 String bucketName = "XXXXX"; //上传到oss后的名字 String objectName = UUID.randomUUID().toString().replace("-","")+myfile.getOriginalFilename(); // 创建OSSClient实例。 /** * String endpoint,自己的endpoint * String accessKeyId, 自己的id * String secretAccessKey自己的密钥 */ String accessKeyId="XXXXXXX"; String secretAccessKey="XXXXXXX"; OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,secretAccessKey); try { InputStream inputStream = myfile.getInputStream(); // 创建PutObjectRequest对象。 PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream); // 创建PutObject请求。 PutObjectResult result = ossClient.putObject(putObjectRequest); } catch (Exception oe) { } finally { if (ossClient != null) { ossClient.shutdown(); } } return "success"; }
3、案例
springmvc+jdbc+elementui+vue
添加和展示所有的功能
3.1 引入相关依赖
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.ykq</groupId> <artifactId>qy174-springmvc04</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.10.RELEASE</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.24</version> </dependency> <!--servlet依赖--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!--jackson依赖:把controller层方法返回的java对象转化为json字符串--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.3</version> </dependency> <!--文件上传依赖--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> <!--oss的依赖--> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.15.1</version> </dependency> <!--mysql的jar--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.28</version> </dependency> <!--druid--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.8</version> </dependency> </dependencies> </project>
3.2 创建实体类
@Data public class Student implements Serializable { private Integer id; private String name; private String phone; private String email; private Integer age; private Byte gender; private Date createtime; private String head; }
3.3 创建controller层
3.3.1 创建StudentController
@Controller @RequestMapping("/student") public class StudentController { private StudentDao studentDao=new StudentDao(); @GetMapping("/list") @ResponseBody //把java对象转化为json字符串 public List<Student> list(){ List<Student> list = studentDao.findAll(); return list; } @PostMapping("/add") @ResponseBody //把java对象转化为json字符串 public int add(@RequestBody Student student){ int add = studentDao.add(student.getName(), student.getPhone(), student.getEmail(), student.getAge(), student.getGender(), student.getHead()); return add; } }
3.3.2 创建UploadController
@Controller public class UploadController { /** * * @param myfile 接受你上传的文件对象信息封装到该类。该类中可以获取上传文件的信息。比如:文件名 文件大小 文件后缀等 * 这个名称必须为文件上传表单的文件框的名称一致 * @return */ @PostMapping("/upload") public String upload(MultipartFile myfile, HttpServletRequest request) throws IOException { //获取tomcat上下文中的指定目录的路径 String realPath = request.getSession().getServletContext().getRealPath("/upload"); //根据上面的路径创建一个文件对象 File file=new File(realPath); //如果没有该目录则创建 if (!file.exists()) { file.mkdirs(); } //把上传的文件转移到upload目录下--重名覆盖了 String uuid = UUID.randomUUID().toString().replace("-", ""); File target=new File(realPath+"/"+(uuid+myfile.getOriginalFilename())); myfile.transferTo(target); return "success"; } @PostMapping("/upload2") @ResponseBody public String upload2(MultipartFile file){ // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。 String endpoint = "oss-cn-beijing.aliyuncs.com"; // 填写Bucket名称,例如examplebucket。 String bucketName = "qy174-8888"; //上传到oss后的名字 String objectName = UUID.randomUUID().toString().replace("-","")+file.getOriginalFilename(); // 创建OSSClient实例。 /** * String endpoint,自己的endpoint * String accessKeyId, 自己的id * String secretAccessKey自己的密钥 * XX * XXX */ String accessKeyId="XXX"; String secretAccessKey="XXX"; OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,secretAccessKey); try { InputStream inputStream = file.getInputStream(); // 创建PutObjectRequest对象。 PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream); // 创建PutObject请求。 PutObjectResult result = ossClient.putObject(putObjectRequest); String path="https://"+bucketName+"."+endpoint+"/"+objectName; return path; } catch (Exception oe) { } finally { if (ossClient != null) { ossClient.shutdown(); } } return "失败"; } }
3.4 创建dao层
3.4.1 BaseDao
public class BaseDao { protected Connection conn; protected PreparedStatement ps; protected ResultSet rs; //数据源对象 private static DataSource dataSource; //静态代码块中 static { try { //创建一个属性对象 Properties properties = new Properties(); //加载属性文件 InputStream inputStream = BaseDao.class.getClassLoader().getResourceAsStream("db.properties"); properties.load(inputStream); //获取连接池对象 dataSource = DruidDataSourceFactory.createDataSource(properties); } catch (Exception e) { e.printStackTrace(); } } //获取连接对象 public void getConn() throws Exception{ conn = dataSource.getConnection(); } //关闭资源 public void closeAll(){ if(rs!=null){ try { rs.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(ps!=null){ try { ps.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(conn!=null){ try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } //通用的增删改方法 public int edit(String sql,Object...params){ try { getConn(); ps=conn.prepareStatement(sql); //为占位符赋值 for(int i=0;i<params.length;i++){ ps.setObject(i+1,params[i]); } int row = ps.executeUpdate(); return row; } catch (Exception e) { e.printStackTrace(); } finally { closeAll(); } return 0; } } /** 1. 四个属性: connection preparedStatement ResultSet DataSource 2. 静态代码块:[获取连接池] 3. 获取连接对象的方法 4. 关闭资源方法 5. 通用的增删改方法 */
3.4.2 StudentDao
public class StudentDao extends BaseDao { //求总条数 select count(*) from t_student public int getCount(){ try { getConn(); String sql="select count(*) as c from t_student"; ps=conn.prepareStatement(sql); rs=ps.executeQuery(); while (rs.next()){ int c = rs.getInt("c"); return c; } } catch (Exception e) { e.printStackTrace(); } finally { closeAll(); } return 0; } //查询所有学员信息--单元测试 public List<Student> findAll(){ List<Student> list=new ArrayList<Student>(); try { getConn(); String sql="select * from t_student"; ps=conn.prepareStatement(sql); rs=ps.executeQuery(); while (rs.next()){ Student s=new Student(); s.setId(rs.getInt("id")); s.setPhone(rs.getString("phone")); s.setEmail(rs.getString("email")); s.setAge(rs.getInt("age")); s.setName(rs.getString("name")); s.setCreatetime(rs.getDate("createtime")); s.setGender(rs.getByte("gender")); s.setHead(rs.getString("head")); list.add(s); } } catch (Exception e) { e.printStackTrace(); } finally { closeAll(); } return list; } //根据id查询学员信息 public Student findById(String id){ Student s=null; try { getConn(); String sql="select * from t_student where id=?"; ps=conn.prepareStatement(sql); ps.setObject(1,id); rs=ps.executeQuery(); while (rs.next()){ s=new Student(); s.setId(rs.getInt("id")); s.setPhone(rs.getString("phone")); s.setEmail(rs.getString("email")); s.setAge(rs.getInt("age")); s.setName(rs.getString("name")); s.setCreatetime(rs.getDate("createtime")); s.setGender(rs.getByte("gender")); s.setHead(rs.getString("head")); } } catch (Exception e) { e.printStackTrace(); } finally { closeAll(); } return s; } //添加方法 public int add(String name,String phone,String email,int age,int gender,String head){ String sql="insert into t_student(id,name,phone,email,age,createtime,gender,head) values(null,?,?,?,?,now(),?,?)"; return edit(sql,name,phone,email,age,gender,head); } //修改 public int update(String id,String name,String phone,String email,int age,int gender){ String sql="update t_student set name=?,phone=?,email=?,age=?,gender=?,createtime=now() where id=?"; return edit(sql,name,phone,email,age,gender,id); } //删除方法 public int delete(String id){ String sql="delete from t_student where id=?"; return edit(sql,id); }
3.5 配置SpringMvc配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--com.ykq 扫描该包以及该包下的子包--> <context:component-scan base-package="com.Hs"/> <!--开启注解驱动 不要导错mvc 默认使用的不是注解模式--> <mvc:annotation-driven/> <!--放行静态资源--> <mvc:default-servlet-handler/> <!--视图解析--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/views/"/> <property name="suffix" value=".jsp"/> </bean> <!--文件上传解析器 id:必须为multipartResolver--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--设置文件上传的大小 单位为byte字节 1M=1024kb=1024b 10*1024*1024--> <property name="maxUploadSize" value="10485760"/> <!--设置编码--> <property name="defaultEncoding" value="utf-8"/> </bean> </beans>
3.6 编写upload.jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%--表单: 提交方式必须为post enctype编码:multipart/form-data文件编码--%> <form method="post" action="/upload2" enctype="multipart/form-data"> <%--input必须设置文件文件框 而且必须起名称--%> 选择上传的文件:<input type="file" name="myfile"/><br> <input type="submit" value="上传"/> </form> </body> </html>