一、首先安装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. jmeter 使用问题

    问题1:导入脚本失败,提示 解决:没有安装JMemter plugins manager插件,具体安装参考http://www.cnblogs.com/cxx1/p/7883820.html,第二步.

  2. 小甲鱼Python第十七讲课后习题

    笔记: 1.分清楚形参和实参 2.函数文档:是函数的一部分,于解释不同,使用help(函数名)或者 函数名__doc__可以查看到 3.关键字参数(在一个函数的参数较多的时候作用比较明显): 给参数的 ...

  3. 问题10:获取当前页面宽度JS

    var mleft=document.getElementById("mleft"); var h = document.documentElement.clientHeight; ...

  4. Wireshark简单使用教程2——附视频

    视频链接https://www.bilibili.com/video/av35336089/ 目录 对抓取的流量包进行简单的说明 Wireshark的捕获过滤器和显示过滤器 内容 1.对抓取的流量包进 ...

  5. Servlet实践--HelloWorld

    Servlet规范是一套技术标准,包含与Web应用相关的一系列接口,而具体的Servlet容器负责提供标准的实现,如Tomcat. Servlet的实例对象由Servlet容器负责创建,Servlet ...

  6. python语法_字符串

    字符串 a = 'asdb' #双引号和打印号没区别, 操作 "abc"*2 打印两遍"abc"  #字符串 加* 重复打印字符串 “abc”[2:1] #切片 ...

  7. LeetCode 81 - 搜索旋转排序数组 II - [二分+暴力]

    假设按照升序排序的数组在预先未知的某个点上进行了旋转. ( 例如,数组 [0,0,1,2,2,5,6] 可能变为 [2,5,6,0,0,1,2] ). 编写一个函数来判断给定的目标值是否存在于数组中. ...

  8. 如何print 输出不换行(2 和 3 处理方式 不一样)

    2.7    正常情况下print输出的时候会自动进行换行处理,我们肯定有时候会有输出不换行的需求, 下面开始介绍如何不换行输出: 例子: print("hello world") ...

  9. sqlhelp3

    using System; using System.Collections; using System.Collections.Specialized; using System.Data; usi ...

  10. javascript 表达式

    //    for(表达式1;表达式2;表达式3){//        循环体语句;//    }//    先执行表达式1,在执行2表达式,//        如果2表达式结果为false,退出循环 ...