- java 运行环境:jdk11
- 数据库:sqlite3(版本不限)
- 任务:使用一个springboot作为基础做一个文件上传下载
- 要求:
1:上传的文件先进行sha256加密,将摘要值保存至数据库;
2.将文件进行压缩、保存至项目当前路径下的uplaodfile目录下
3.下载
1:添加依赖
4.0.0 org.springframework.boot spring-boot-starter-parent 2.5.6 com.example uploaddemo 0.0.1-SNAPSHOT uploaddemo uploaddemo 11 org.projectlombok lombok org.springframework.boot spring-boot-starter-web org.xerial sqlite-jdbc com.baomidou mybatis-plus-boot-starter 3.0.5 io.springfox springfox-swagger2 2.9.2 io.springfox springfox-swagger-ui 2.9.2 org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin org.projectlombok lombok
2:安装数据库和jdk11
安装jdk11文章:
https://www.cnblogs.com/hejh/p/11276434.html
安装数据库sqlite3文章:
https://www.runoob.com/sqlite/sqlite-installation.html
https://www.cnblogs.com/oukele/p/9540293.html
3:编写yml
#存放位置
file:
path: E:uploadfile
algo: SHA-256
#数据源
Spring:
datasource:
driver-class-name: org.sqlite.JDBC
url: jdbc:sqlite:E:\test.db
username:
password:
#端口
server:
port: 8888
4:编写controller
下载:
package com.example.uploaddemo.controller;
import com.example.uploaddemo.model.Upload;
import com.example.uploaddemo.service.MyFileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.zip.ZipInputStream;
@Slf4j
@RestController
public class DownLoadController {
@Autowired
private MyFileUploadService myFileUploadService;
@GetMapping(value = "/'download?'")
public void downloadFile(String id , HttpServletRequest request , HttpServletResponse response){
Upload byId = myFileUploadService.getById(id);
System.out.println(byId+"id的值是");
String name = byId.getName() + byId.getEname();
String path = byId.getPath() +byId.getName()+".zip";
System.out.println(path);
if (!ObjectUtils.isEmpty(byId)) {
//设置为下载
InputStream ips = null;
OutputStream ops = null;
ZipInputStream zops = null;
try {
response.setHeader("Content-Type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8"));
ips = new FileInputStream(path);
zops = new ZipInputStream(ips);
zops.getNextEntry();
ops = response.getOutputStream();
byte[] bytes = new byte[1024];
int len = 0;
while ((len = zops.read(bytes)) != -1) {
ops.write(bytes, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
log.error("未找到该文件");
} catch (IOException e) {
e.printStackTrace();
log.error("发生IO流异常");
} finally {
try {
if (zops != null) {
zops.close();
}
if (ops != null) {
ops.close();
}
if (ips != null) {
ips.close();
}
} catch (IOException e) {
e.printStackTrace();
log.error("发生IO流异常");
}
}
log.info("文件下载成功");
}
log.error("下载发生错误");
}
}
上传:
package com.example.uploaddemo.controller;
import com.example.uploaddemo.model.Upload;
import com.example.uploaddemo.service.MyFileUploadService;
import com.example.uploaddemo.util.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@Slf4j
@RestController
public class FileDemoController {
@Value("${file.path}")
private String path;
@Value("${file.algo}")
private String algo;
@Autowired
@Resource
private MyFileUploadService myFileUploadService;
public final static String SHA_256 = "SHA-256";
@PostMapping("upload")
public List upload(MultipartFile file) {
log.info("进入上传的文件接口");
//文件名
String upName = file.getOriginalFilename();
//后缀名
String exName = upName.substring(upName.lastIndexOf("."));
System.out.println(exName);
//存放的文件名
String l = System.currentTimeMillis() + "";
String targetName = path + l + ".zip";
File parent = new File(path);
if (!parent.exists()) {
parent.mkdirs();
}
File targetFile = new File(targetName);
OutputStream ops = null;
ZipOutputStream zops = null;
InputStream ips = null;
try {
ips = file.getInputStream();
ops = new FileOutputStream(targetFile);
zops = new ZipOutputStream(ops);
zops.putNextEntry(new ZipEntry(upName));
MessageDigest instance = MessageDigest.getInstance(algo);
MessageDigest messageDigest;
String encodeStr = "";
messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(file.getBytes());
encodeStr = byte2Hex(messageDigest.digest());
System.out.println("这个是转成功的值"+encodeStr);
String sha256 = FileUtils.bytes2HexString(instance.digest());
byte[] bytes = new byte[1024];
int len = 0;
while (((len = ips.read(bytes)) != -1)) {
zops.write(bytes, 0, len);
}
Upload upload = new Upload();
upload.setId(encodeStr);
upload.setName(l);
upload.setEname(exName);
upload.setPath(path);
upload.setSha256(encodeStr);
myFileUploadService.save(upload);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (zops != null) {
zops.close();
}
if (ops != null) {
ops.close();
}
if (ips != null) {
ips.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
List list = myFileUploadService.list(null);
return list;
}
private static String byte2Hex(byte[] bytes){
StringBuffer stringBuffer = new StringBuffer();
String temp = null;
for (int i=0;i
5:编写service业务类
package com.example.uploaddemo.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.uploaddemo.model.Upload;
public interface MyFileUploadService extends IService {
}
实现类
package com.example.uploaddemo.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.uploaddemo.mapper.FileUploadMapper;
import com.example.uploaddemo.model.Upload;
import com.example.uploaddemo.service.MyFileUploadService;
import org.springframework.stereotype.Service;
@Service
public class MyFileUploadServiceImpl extends ServiceImpl implements MyFileUploadService {
}
6:编写mapper类
package com.example.uploaddemo.mapper;
import com.baomidou.mybatisplus.core.mapper.baseMapper;
import com.example.uploaddemo.model.Upload;
public interface FileUploadMapper extends baseMapper {
}
7:编写加密的工具类
package com.example.uploaddemo.util;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@Slf4j
public class FileUtils {
public static void uploadZip(InputStream inputStream, File target, String filename) {
OutputStream outputStream = null;
ZipOutputStream zipOutputStream = null;
try {
outputStream = new FileOutputStream(target);
zipOutputStream = new ZipOutputStream(outputStream);
zipOutputStream.putNextEntry(new ZipEntry(filename));
byte[] bytes = new byte[1024];
int len = 0;
while ((len = inputStream.read(bytes)) != -1) {
zipOutputStream.write(bytes, 0, len);
}
//关闭流
if (zipOutputStream != null) {
zipOutputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static String toEncryption(byte[] bytes, String algo, String mima) {
String s = "";
try {
//创建加密的实例,选择算法
MessageDigest instance = MessageDigest.getInstance(algo);
instance.update(mima.getBytes(StandardCharsets.UTF_8));
s = bytes2HexString(instance.digest());
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
public static String bytes2HexString(byte[] bytes) {
StringBuffer sb = new StringBuffer(bytes.length);
String sTemp;
for (int i = 0; i < bytes.length; i++) {
sTemp = Integer.toHexString(0xFF & bytes[i]);
if (sTemp.length() < 2) {
sb.append(0);
}
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
}
8:编写前端:在resources/static/下
上传下载图片
9:测试和效果的展示:



