一、首先安装mysql数据库,开启web服务器。

二、pom.xml文件依赖包配置如下:

<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <groupId>com.weChat</groupId>
<artifactId>SmallProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SmallProject</name>
<description>Demo project for Spring Boot</description> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency> </dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

二、使用IDE建立springboot+web工程,连接数据库的application.properties配置如下:

 1 #服务器端口设置
2 server.port=8080
3 #必须包含项目名称
4 #server.servlet.context-path=/demo
5 #数据库配置信息
6 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
7 spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&useSSL=false
8 spring.datasource.username=root
9 spring.datasource.password=******
10 #设置单个上传文件的大小
11 spring.servlet.multipart.max-file-size=200GB
12 #设置一次请求上传文件的总量
13 spring.servlet.multipart.max-request-size=200GB
14 spring.jpa.hibernate.ddl-auto=update
15 spring.jpa.show-sql=true

三、建立数据库表格的Test.java内容如下:

 package com.wechat.smallproject.dataBaseTable;

 import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date; /**
* @Author CFF
* @Date:Created in 16:25 2019/1/10
*/
@Table(name = "picture_info")
@Entity
public class Test {
@Id
/**
* 主键ID
*/
@Column(length = 32)
private Integer Id;
/**
* 图片名称
*/
private String pictureName;
/**
* 图片格式
*/
private String pictureFormat;
/**
* 图片上传存放地址
*/
private String picturePath;
/**
* 图片上传大小
*/
private long pictureSize;
/**
* 上传图片时间
*/
private Date uploadPictureTime; public Integer getId() {
return Id;
} public void setId(Integer id) {
Id = id;
} public String getPictureName() {
return pictureName;
} public void setPictureName(String pictureName) {
this.pictureName = pictureName;
} public String getPictureFormat() {
return pictureFormat;
} public void setPictureFormat(String pictureFormat) {
this.pictureFormat = pictureFormat;
} public String getPicturePath() {
return picturePath;
} public void setPicturePath(String picturePath) {
this.picturePath = picturePath;
} public long getPictureSize() {
return pictureSize;
} public void setPictureSize(long pictureSize) {
this.pictureSize = pictureSize;
} public Date getUploadPictureTime() {
return uploadPictureTime;
} public void setUploadPictureTime(Date uploadPictureTime) {
this.uploadPictureTime = uploadPictureTime;
} }

四、建立TestDao.java接口,用来保存数据库表信息:

 package com.wechat.smallproject.dao;

 import com.wechat.smallproject.dataBaseTable.Test;
import org.springframework.data.jpa.repository.JpaRepository; /**
* @Author CFF
* @Date:Created in 16:45 2019/1/10
*/
public interface TestDao extends JpaRepository<Test,Integer> {
}

五、建立TestController.java,编写文件上传和下载方法。

 package com.wechat.smallproject.controller;

 import com.wechat.smallproject.dao.TestDao;
import com.wechat.smallproject.dataBaseTable.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*; /**
* @Author CFF
* @Date:Created in 16:47 2019/1/10
*/
@RestController
public class TestController {
@Autowired
TestDao testDao; public String pictureName=null ;
public String picturePath=null ; @RequestMapping(value = "/upload")
public void uploadPicture(HttpServletRequest request) throws Exception {
//获取文件需要上传到的路径
picturePath = "C:\\Users\\CFF\\Desktop\\Project\\PicturesPath\\"; // 判断存放上传文件的目录是否存在(不存在则创建)
File dir = new File(picturePath);
if (!dir.exists()) {
dir.mkdir();
}
try {
StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
//获取formdata的值
Iterator<String> iterator = req.getFileNames();
while (iterator.hasNext()) {
MultipartFile file=req.getFile(iterator.next());
//获取文件后缀名
String fileSuffixName=file.getOriginalFilename().substring(86);
//真正写到磁盘上
//全球唯一id
String uuid= UUID.randomUUID().toString().replace("-","");
pictureName=uuid+fileSuffixName;
//将文件信息存入数据库中
Test test =new Test();
if(new Date().hashCode()<0){
test.setId(-new Date().hashCode());
}
else{
test.setId(new Date().hashCode());
}
test.setUploadPictureTime(new Date());
test.setPictureName(uuid);
test.setPicturePath(picturePath+pictureName);
test.setPictureSize(file.getSize());
test.setPictureFormat(file.getContentType());
testDao.save(test); File file1=new File(picturePath+pictureName);
OutputStream out=new FileOutputStream(file1);
out.write(file.getBytes());
out.close();
System.out.println("图片上传成功!");
}
} catch (Exception e) {
System.out.println(e);
}
}
//文件下载相关代码
@RequestMapping("/download")
public void fileDownload( HttpServletResponse response){
File file = new File(picturePath+pictureName);
if (pictureName != null) {
if (file.exists()) {
response.setContentType("application/force-download");// 设置强制下载不打开
Date currentTime = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String dataTime=dateFormat.format(currentTime);
//文件重新命名
String pictureNewName = dataTime+pictureName.substring(pictureName.indexOf("."));
response.addHeader("Content-Disposition",
"attachment;fileName=" + pictureNewName);// 设置文件名
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println(pictureNewName+"下载成功!!!");
} catch (Exception e) {
e.printStackTrace();
System.out.println(pictureNewName+"下载失败!!!"+e);
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}

六、upload.html如下:

 <!DOCTYPE html>
<html lang="en">
<head>
<title>上传图片</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
文件:<input type="file" name="filename"/>
<input type="submit" value="提交"/>
</form>
<a href="/download">下载</a>
</body>
</html>
 

springboot+web文件上传和下载的更多相关文章

  1. SpringBoot下文件上传与下载的实现

    原文:http://blog.csdn.net/colton_null/article/details/76696674 SpringBoot后台如何实现文件上传下载? 最近做的一个项目涉及到文件上传 ...

  2. SpringBoot整合阿里云OSS文件上传、下载、查看、删除

    1. 开发前准备 1.1 前置知识 java基础以及SpringBoot简单基础知识即可. 1.2 环境参数 开发工具:IDEA 基础环境:Maven+JDK8 所用技术:SpringBoot.lom ...

  3. SpringBoot图文教程4—SpringBoot 实现文件上传下载

    有天上飞的概念,就要有落地的实现 概念+代码实现是本文的特点,教程将涵盖完整的图文教程,代码案例 文章结尾配套自测面试题,学完技术自我测试更扎实 概念十遍不如代码一遍,朋友,希望你把文中所有的代码案例 ...

  4. java web学习总结(二十四) -------------------Servlet文件上传和下载的实现

    在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...

  5. java web 文件上传下载

    文件上传下载案例: 首先是此案例工程的目录结构:

  6. WEB文件上传下载功能

    WEB文件上传下载在日常工作中经常用到的功能 这里用到JS库 http://files.cnblogs.com/meilibao/ajaxupload.3.5.js 上传代码段(HTML) <% ...

  7. SpringBoot 文件上传、下载、设置大小

    本文使用SpringBoot的版本为2.0.3.RELEASE 1.上传单个文件 ①html对应的提交表单 <form action="uploadFile" method= ...

  8. 简单的文件上传的下载(动态web项目)

    1.在页面中定义一个form表单,如下: <!-- 文件上传 --> <form action="${pageContext.request.contextPath}/Fi ...

  9. SpringMVC整合fastdfs-client-java实现web文件上传下载

    原文:http://blog.csdn.net/wlwlwlwl015/article/details/52682153 本篇blog主要记录一下SpringMVC整合FastDFS的Java客户端实 ...

随机推荐

  1. 关于UTF-8和GBK编码的转换

    $oldname=mb_convert_encoding($_POST['oldname'], "GBK" , "UTF-8");//将变量转码为GBK,已知原 ...

  2. JavaScript 特效之四大家族(offset/scroll/client/event)

      三大系列:offset.scroll.client 事件对象:event(事件被触动时,鼠标和键盘的状态)(通过属性控制)   三大系列都是以DOM元素节点的属性形式存在的. 类比访问关系,也是以 ...

  3. (71)Wangdao.com第十一天_JavaScript 数学对象 Math

    Math 对象 封装了数学相关的 属性和方法. 和其他对象不一样,Math 不是一个构造函数,所以不能 new 生成实例, 其所有属性和方法都必须在 Math 对象上调用. 静态属性 Math.PI ...

  4. (AB)Codeforces Round #528 (Div. 2, based on Technocup 2019 Elimination Round

    A. Right-Left Cipher time limit per test 1 second memory limit per test 256 megabytes input standard ...

  5. python dgango简介 安装 多表查询

    一.socket服务器 import socket sk=socket.socket() sk.bind(("127.0.0.1",8890)) sk.listen() while ...

  6. python中的基础2

    2 2.1 字符串的索引与切片: a = 'ABCDEFGHIJK' print(a[0]) print(a[3]) print(a[5]) print(a[7]) 2.2  字符串的常用方法. pr ...

  7. Maven的安装、配置及使用入门+maven安装报错:JAVA_HOME【申明:来源于网络】

    Maven的安装.配置及使用入门+maven安装报错:JAVA_HOME[申明:来源于网络] Maven的安装.配置及使用入门:http://www.cnblogs.com/dcba1112/arch ...

  8. archlinux下安装acroread打开pdf

    虽说acroread是个好东西,但是在打开pdf几秒后总是自动退出呢 在其aur网页下找到了这么一解决办法: 打开终端输入 sudo unshare -n sudo -u ${USER} ACRO_A ...

  9. java_基础_static{}语句块

    static{}语句块会在类被加载的时候当且仅当执行一次,一般用于初始化变量和调用静态方法 Class.forName(“类名”);方法执行时会加载类 外界调用类中静态变量是不会加载类的,也就是说,如 ...

  10. Lombok 介绍

    Lombok使用 介绍 在项目中使用Lombok可以减少很多重复代码的书写.比如说getter/setter/toString等方法的编写. IDEA中的安装 打开IDEA的Setting –> ...