springboot+web文件上传和下载

一、首先安装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>
 
上一篇:vs2008试用期到期解决办法


下一篇:asp.net中使用swfupload上传大文件