文件上传与下载(sha256加密)

技术:springboot、mybatisplus
目标:
  • java 运行环境:jdk11
  • 数据库:sqlite3(版本不限)
  • 任务:使用一个springboot作为基础做一个文件上传下载
  • 要求:
    1:上传的文件先进行sha256加密,将摘要值保存至数据库;
    2.将文件进行压缩、保存至项目当前路径下的uplaodfile目录下
    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 https://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.5.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>uploaddemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>uploaddemo</name>
    <description>uploaddemo</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
<!--        小辣椒-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
<!--        驱动-->
        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
        </dependency>
<!--        mybatis的依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.5</version>
        </dependency>
        <!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

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> 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<Upload> list = myFileUploadService.list(null);
        return list;
    }

    private static String byte2Hex(byte[] bytes){
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i=0;i<bytes.length;i++){
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length()==1){

                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }
}

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<Upload> {

}

实现类

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<FileUploadMapper, Upload> 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<Upload> {

}

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/下

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>上传下载图片</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
  <input type="file" id="file" name="file">
  <input type="submit" value="上传">
</form>
</body>
</html>

9:测试和效果的展示:

文件上传与下载(sha256加密)
文件上传与下载(sha256加密)

Original: https://blog.csdn.net/weixin_55604133/article/details/121030876
Author: 程序员小小刘
Title: 文件上传与下载(sha256加密)

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/816223/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球