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方法,从而显示出来。
这些工具类还可以用于图片上传。这个就放到下期吧!
本文地址:https://blog.csdn.net/weixin_42596407/article/details/107363717
上一篇: AOP简介