目录
1.MD5加密算法
import java.security.MessageDigest;
/**
* 该方法为MD5加密算法
*
* @param
* @return
*
*/
public class MD5 {
private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
public static String byteArrayToHexString(byte[] b) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++) {
resultSb.append(byteToHexString(b[i]));
}
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n = 256 + n;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
public static String MD5Encode(String origin) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
resultString = byteArrayToHexString(md.digest(resultString
.getBytes()));
} catch (Exception ex) {
}
return resultString;
}
public static String MD5Encode(String origin, String encodding) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
resultString = byteArrayToHexString(md.digest(resultString
.getBytes(encodding)));
} catch (Exception ex) {
}
return resultString;
}
}
2.文件上传
Java的文件上传一共涉及两个组件,CommonsMultipartResolver和StandaServletMutipartResolver。其中前者使用commons-fileupload处理multipart请求,后者则基于Servlet3.0处理multipart请求,所以使用后者不需要额外的jar包。可以直接使用。
直接使用
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
/**
* Created by tomasonl;
*/
@RestController
public class FileUploadController {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
@PostMapping("/upload")
public String upload(MultipartFile uploadFile, HttpServletRequest req) throws FileNotFoundException {
String realPath = req.getSession().getServletContext().getRealPath("/uploadFile/");
System.out.println(realPath);
String format = sdf.format(new Date());
File folder = new File(realPath + format);
if (!folder.isDirectory()) {
folder.mkdirs();
}
String oldName = uploadFile.getOriginalFilename();
String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
try {
uploadFile.transferTo(new File(folder, newName));
String filePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/uploadFile/" + format + newName;
return filePath;
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败!";
}
@PostMapping("/uploads")
public String upload(MultipartFile[] uploadFiles, HttpServletRequest req) {
for (MultipartFile uploadFile : uploadFiles) {
String realPath = req.getSession().getServletContext().getRealPath("/uploadFile/");
System.out.println(realPath);
String format = sdf.format(new Date());
File folder = new File(realPath + format);
if (!folder.isDirectory()) {
folder.mkdirs();
}
String oldName = uploadFile.getOriginalFilename();
String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
try {
uploadFile.transferTo(new File(folder, newName));
String filePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/uploadFile/" + format + newName;
return filePath;
} catch (IOException e) {
e.printStackTrace();
}
}
return "上传失败!";
}
}
方式二
import org.apache.commons.io.FileUtils;
import org.springframework.util.ResourceUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
* SpringBoot上传文件工具类
* 要引入依赖
* <dependency>
* <groupId>commons-io</groupId>
* <artifactId>commons-io</artifactId>
* <version>2.4</version>
* </dependency>
* <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
* <dependency>
* <groupId>commons-fileupload</groupId>
* <artifactId>commons-fileupload</artifactId>
* <version>1.3.1</version>
* </dependency>
*/
public class FileHandleUtil {
/** 绝对路径 **/
private static String absolutePath = "";
/** 静态目录 **/
private static String staticDir = "static";
/** 文件存放的目录 **/
private static String fileDir = "/upload/";
/**
* 上传单个文件
* 最后文件存放路径为:static/upload/image/test.jpg
* 文件访问路径为:http://127.0.0.1:8080/upload/image/test.jpg
* 该方法返回值为:/upload/image/test.jpg
* @param inputStream 文件流
* @param path 文件路径,如:image/
* @param filename 文件名,如:test.jpg
* @return 成功:上传后的文件访问路径,失败返回:null
*/
public static String upload(InputStream inputStream, String path, String filename) {
//第一次会创建文件夹
createDirIfNotExists();
String resultPath = fileDir + path + filename;
//存文件
File uploadFile = new File(absolutePath, staticDir + resultPath);
try {
FileUtils.copyInputStreamToFile(inputStream, uploadFile);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return resultPath;
}
/**
* 创建文件夹路径
*/
private static void createDirIfNotExists() {
if (!absolutePath.isEmpty()) {return;}
//获取跟目录
File file = null;
try {
file = new File(ResourceUtils.getURL("classpath:").getPath());
} catch (FileNotFoundException e) {
throw new RuntimeException("获取根目录失败,无法创建上传目录!");
}
if(!file.exists()) {
file = new File("");
}
absolutePath = file.getAbsolutePath();
File upload = new File(absolutePath, staticDir + fileDir);
if(!upload.exists()) {
upload.mkdirs();
}
}
/**
* 删除文件
* @param path 文件访问的路径upload开始 如: /upload/image/test.jpg
* @return true 删除成功; false 删除失败
*/
public static boolean delete(String path) {
File file = new File(absolutePath, staticDir + path);
if (file.exists()) {
return file.delete();
}
return false;
}
}
3.验证码
package com.example.tools;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.imageio.ImageIO;
import org.apache.commons.codec.binary.Base64;
/**
* 该方法为验证码图片生成工具
*
* @param
* @return
*
*/
public class CaptchaUtils {
private static final String CAPTCHA_STRING = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
private static final Random random = new Random();
/**
* 该方法为生成图片验证码
*
* @param width 生成的验证码宽度
* @param height 生成的验证码高度
* @return
*
*/
public static Map<String, String> generateImageCaptcha(int width, int height) throws Exception {
String encoderBase64Str = null;
Map<String, String> captchaMap = new HashMap<String, String>();
if(width <= 0) {
width = 200;
}
if(height <= 0) {
height = 80;
}
String captchaString = generateCaptcha(4);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
outputImage(width, height, byteArrayOutputStream, captchaString);
byte[] byteArray = byteArrayOutputStream.toByteArray();
byteArray = Base64.encodeBase64(byteArray);
encoderBase64Str = new String(byteArray);
captchaMap.put(captchaString, encoderBase64Str);
return captchaMap;
}
private static String generateCaptcha(int captchaSize) {
return generateCaptcha(captchaSize, CAPTCHA_STRING);
}
private static String generateCaptcha(int captchaSize, String captchaString) {
if (captchaSize == 0 || CheckFormatUtils.isEmpty(captchaString)) {
captchaString = CAPTCHA_STRING;
}
int captchaLength = captchaString.length();
Random captchaRandom = new Random(System.currentTimeMillis());
StringBuilder stringBuilder = new StringBuilder(captchaSize);
for (int i = 0; i < captchaSize; i++) {
stringBuilder.append(captchaString.charAt(captchaRandom
.nextInt(captchaLength - 1)));
}
return stringBuilder.toString();
}
public static String outputCaptchaImage(int width, int height,
File outputFile, int captchaSize) throws IOException {
String captchaString = generateCaptcha(captchaSize);
outputImage(width, height, outputFile, captchaString);
return captchaString;
}
public static String outputCaptchaImage(int width, int height,
OutputStream outputStream, int captchaSize) throws IOException {
String captchaString = generateCaptcha(captchaSize);
outputImage(width, height, outputStream, captchaString);
return captchaString;
}
public static void outputImage(int width, int height, File outputFile,
String captchaString) throws IOException {
FileOutputStream fos = null;
if (outputFile == null) {
return;
}
File dir = outputFile.getParentFile();
if (!dir.exists()) {
dir.mkdirs();
}
try {
outputFile.createNewFile();
fos = new FileOutputStream(outputFile);
outputImage(width, height, fos, captchaString);
} catch (IOException e) {
throw e;
} finally {
if (fos != null) {
fos.close();
}
}
}
public static ByteArrayOutputStream outputImage(int width, int height,
OutputStream outputStream, String captchaString) throws IOException {
int captchaLength = captchaString.length();
BufferedImage bufferedImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Random colorsRandom = new Random();
Graphics2D graphics2D = bufferedImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Color[] colors = new Color[5];
Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
Color.PINK, Color.YELLOW };
float[] fractions = new float[colors.length];
for (int i = 0; i < colors.length; i++) {
colors[i] = colorSpaces[colorsRandom.nextInt(colorSpaces.length)];
fractions[i] = colorsRandom.nextFloat();
}
Arrays.sort(fractions);
graphics2D.setColor(Color.GRAY);
graphics2D.fillRect(0, 0, width, height);
Color color = getRandColor(200, 250);
graphics2D.setColor(color);
graphics2D.fillRect(0, 2, width, height - 4);
Random random = new Random();
graphics2D.setColor(getRandColor(160, 200));
for (int i = 0; i < 20; i++) {
int x = random.nextInt(width - 1);
int y = random.nextInt(height - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
graphics2D.drawLine(x, y, x + xl + 40, y + yl + 20);
}
float yawpRate = 0.05f;
int area = (int) (yawpRate * width * height);
for (int i = 0; i < area; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int rgb = getRandomIntColor();
bufferedImage.setRGB(x, y, rgb);
}
shear(graphics2D, width, height, color);
graphics2D.setColor(getRandColor(100, 160));
int fontSize = height - 4;
Font font = new Font("Algerian", Font.ITALIC, fontSize);
graphics2D.setFont(font);
char[] chars = captchaString.toCharArray();
for (int i = 0; i < captchaLength; i++) {
AffineTransform affine = new AffineTransform();
affine.setToRotation(Math.PI / 4 * colorsRandom.nextDouble()
* (colorsRandom.nextBoolean() ? 1 : -1),
(width / captchaLength) * i + fontSize / 2, height / 2);
graphics2D.setTransform(affine);
graphics2D.drawChars(chars, i, 1, ((width - 10) / captchaLength)
* i + 5, height / 2 + fontSize / 2 - 10);
}
graphics2D.dispose();
ImageIO.write(bufferedImage, "jpg", outputStream);
return (ByteArrayOutputStream) outputStream;
}
private static Color getRandColor(int fc, int bc) {
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
private static int getRandomIntColor() {
int[] rgb = getRandomRgb();
int color = 0;
for (int c : rgb) {
color = color << 8;
color = color | c;
}
return color;
}
private static int[] getRandomRgb() {
int[] rgb = new int[3];
for (int i = 0; i < 3; i++) {
rgb[i] = random.nextInt(255);
}
return rgb;
}
private static void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}
private static void shearX(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(2);
boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}
}
private static void shearY(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(40) + 10;
boolean borderGap = true;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}
}
}
}