jSignature签名的用法,一文教会你(二)后台代码

1、先在我们的项目里加几个工具类,代码如下

AbstractUploadAction (名字可以自取,这个不影响)


import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.IOUtils;
public abstract class AbstractUploadAction {
	
	public void get(HttpServletRequest request, HttpServletResponse response, String storeDir) {
        String requestPath = "get";
        String requestURI = request.getRequestURI();
        String path = requestURI.substring(requestURI.indexOf(requestPath) + 3);
        String separator = File.separator;
        String lcPath = "";
        File directory = new File(storeDir);
        String tempPath = directory.getAbsolutePath() + path.replace("/", separator);
        File downloadFile = new File(tempPath);
        if (downloadFile.exists()) {
            lcPath = directory.getAbsolutePath() + path.replace("/", separator);
        }

        try {
            InputStream input = new FileInputStream(lcPath);
            OutputStream output = response.getOutputStream();
            IOUtils.copy(input, output);
            input.close();
            output.close();
        } catch (Exception var14) {
        }

    }

}

UploadFileAction 这里有一个@Value("${store.dir}") private String storeDir; 这是在yml里面的定义的,这里就是把文件放在我的D盘下的ms_file文件夹下面在这里插入图片描述

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/res/file")
public class UploadFileAction extends AbstractUploadAction{
	
	@Value("${store.dir}")
	private String storeDir;//这个是在yml里面定义的
	
	
	/**
	 * 
	 * @param folder 文件文件夹。即分类文件夹。如imgType1,imgType2。通过url的upload/后面的值来取值。也可换为其他取值方式。
	 * @param request
	 * @return
	 * @throws IOException
	 */
    @RequestMapping(
        value = {"upload/{folder}"},
        method = {RequestMethod.POST, RequestMethod.GET}
    )
    @ResponseBody
    public Object upload(@PathVariable("folder") String folder, HttpServletRequest request) throws IOException {
    	UploadFileUtil uploadFileUtil = new UploadFileUtil();
    	return uploadFileUtil.upload(storeDir, folder, request);
    }
	
	@RequestMapping("/get/**")
    public void download(HttpServletRequest request, HttpServletResponse response) {
        this.get(request, response, this.storeDir);
    } 

}

UploadUtil


import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

public class UploadUtil {

	
    public static void copyFile(MultipartFile file, File locFile) throws IOException {
        InputStream input = file.getInputStream();
        OutputStream output = new FileOutputStream(locFile);
        IOUtils.copy(input, output);
        output.close();
        input.close();
    }
    
    /**
     *
     * @param requestUri 这个是数据库的url,如/res/file/get/signature/20200709114433.jpg
     * @param fileDir 这个是文件的实际存放地址,如D://ms_file
     * @return
     */
    public static boolean delete(String requestUri, String fileDir) {
        String requestPath = "get";
        String path = requestUri.substring(requestUri.indexOf(requestPath) + 3);
        //File directory = new File(fileDir);
        //String tempPath = directory.getAbsolutePath() + path;
        String tempPath = fileDir + path;
        File deleteFile = new File(tempPath);
        return deleteFile.exists() ? deleteFile.delete() : false;
    }

}

Base64ToPicture (这个是base64和图片互转的一个工具类)

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.util.Base64;
public class Base64ToPicture {
    
    /**
     * 将base64转成图片并存到指定文件夹
     * @param imgStrs
     * @param imgFilePath
     * @return
     */
    public static boolean GenerateImage(String imgStrs, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片
        if (imgStrs == null){
            // 图像数据为空
            return false;
        }
        int imgStrLen = imgStrs.length();
        String imgStr = imgStrs.substring(22,imgStrLen);
        //System.out.println(imgStr);
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
     * @param imgFilePath
     * @return
     */
    public static String GetImageStr(String imgFilePath) {//
        byte[] data = null;
        Base64.Decoder decoder = Base64.getDecoder();
        
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgFilePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);// 返回Base64编码过的字节数组字符串
    }
}

2、看一下我的service吧

public Result save(ProjectFile projectFile, HttpServletRequest request){
        Result result = new Result();
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileAdd = sdf.format(new Date());
        //图片名称是  当前日期    避免数据重复
        String fileName = fileAdd  + ".jpg";
        //这个Base64ToPicture就是我们上面的工具类
        //这个步骤是把base64转成图片,并存在storeDir+"/signature/"+fileName这个目录下,这个storeDir是我们自己定义的,比如这个是D:/ms_file/signature/
        Base64ToPicture.GenerateImage(projectFile.getEncode(),storeDir+"/signature/"+fileName);
		//下面的步骤是给我们的数据库插入一条关于这个签名的记录,方便我们以后找到他
        String url = "/res/file/get/" + "signature" + "/" + fileName;
        projectFile.setId(UUIDTool.createUUID());
        projectFile.setUrl(url);
        projectFile.setCreateTime(new Date());
        projectFile.setFileType("jpg");
        projectFile.setType("signature");
        projectFile.setName(fileName);
        projectFileMapper.insert(projectFile);
        
        result.setMessage("签名成功!");
        result.setCode(1);
        return result;
    }

这个操作过后我们发现我们的数据库多了一条记录,数据库自己设计,在这里URL我存的是这样的格式的:/res/file/get/signature/20200709114433.jpg,其实我们的文件在D:\ms_file\signature\20200709114433.jpg,我们会发现这里没有指定是哪个盘,哪个文件夹下,反而多了/res/file/get/这串东西,大家别着急,这个是我们自己定义的。我们可以发现UploadFileAction 这个工具类里定义了@RequestMapping("/res/file"),get也是在UploadFileAction 里定义的。我们数据库要和这里保持一致性,大家可以随便定义;

3、查看我们的签名

先去数据库中查到我们需要的那条数据,拿到URL,就也是上面举例的/res/file/get/signature/20200709114433.jpg。
在页面中我们这样显示


http({
	data: {
		projectId:projectId,
		institutionsId:institutionsId
	},
	url: 'projectFile/queryByInstitutionsId',
	type: 'post',
	dataType: 'json',
	success: function(data) {
		that.signatureList = data;
		for(var i = 0;i<that.signatureList.length;i++){
			$("#imageList").append("<img src=http://127.0.0.1:7003" + that.signatureList[i].url + ">");
		}
	}
});

只需要拼接起来就好了,后台端口加我们的URL就可以了,它会去调用我们工具类中的get方法,从而显示出来。

这些工具类还可以用于图片上传。这个就放到下期吧!

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python 中的线程睡眠可以通过 `time.sleep()` 函数来实现,该函数让当前线程暂停指定的时间,单位为秒。例如,以下代码让当前线程睡眠 1 秒钟: ```python import time print("start") time.sleep(1) print("end") ``` 输出: ``` start (end 1 秒钟后输出) ``` 需要注意的是,线程睡眠让当前线程阻塞,即当前线程暂停执行,等待指定的时间后再继续执行。如果在主线程中使用线程睡眠,导致整个程序的执行被暂停。 另外,需要注意的是 Python 中的线程与操作系统的线程并不是一一对应的关系,Python 解释器使用一个全局锁来保证同一时刻只有一个线程在执行 Python 代码。因此,如果在 Python 中使用多线程,可能出现线程间的竞争和阻塞,需要使用适当的同步机制(如锁、信号量等)来解决。 至于后台线程,它是一种特殊的线程,在程序退出时自动结束,不需要等待其执行完成。可以通过设置线程对象的 `daemon` 属性来创建后台线程。例如,以下代码创建了一个后台线程: ```python import threading import time def count(): for i in range(5): print(i) time.sleep(1) t = threading.Thread(target=count) t.daemon = True t.start() print("main thread exit") ``` 输出: ``` 0 main thread exit 1 2 3 4 ``` 注意,当主线程退出时,后台线程也随之结束,即使后台线程没有执行完毕。因此,需要确保后台线程的执行时间不超过主线程的生命周期。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值