返回的是是相对路径的图片连接
package com.zkc.student.controller;
import com.zkc.student.utils.DigestUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.Date;
@Controller
public class ImgUplod {
public static final String IMAGE_PNG = "image/png";
public static final String IMAGE_JPG = "image/jpg";
public static final String IMAGE_JPEG = "image/jpeg";
public static final String IMAGE_BMP = "image/bmp";
public static final String IMAGE_GIF = "image/gif";
public static final int DEFAULT_FILE_NAME_LENGTH = 100;
public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;
public static final String[] DEFAULT_ALLOWED_EXTENSION = {
"bmp", "gif", "jpg", "jpeg", "png",
"doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt",
"rar", "zip", "gz", "bz2",
"pdf"};
public static final String[] IMAGE_EXTENSION = {"bmp", "gif", "jpg", "jpeg", "png"};
public static final String[] FLASH_EXTENSION = {"swf", "flv"};
public static final String[] MEDIA_EXTENSION = {"swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg", "asf", "rm", "rmvb"};
private static int counter = 0;
@PostMapping("/uplod")
@ResponseBody
public String Uplod(@RequestParam("imgFile") MultipartFile imgFile) throws IOException {
if (imgFile.isEmpty()) {
return "请上传图片!";
}
File fileDir = new File("/student");
if (!fileDir.isDirectory()) {
fileDir.mkdirs();
}
int ImgFileNamelength = imgFile.getOriginalFilename().length();
if (ImgFileNamelength > DEFAULT_FILE_NAME_LENGTH) {
return "图片名字长度超过100";
}
long ImgFileSize = imgFile.getSize();
if (DEFAULT_MAX_SIZE != -1 && ImgFileSize > DEFAULT_MAX_SIZE) {
return "图片大小超过50M";
}
String extension = FilenameUtils.getExtension(imgFile.getOriginalFilename());
if (StringUtils.isEmpty(extension)) {
extension = Extension(imgFile.getContentType());
}
String ImgFileName = imgFile.getOriginalFilename();
if (DEFAULT_ALLOWED_EXTENSION != null && !isAllowedExtension(extension, DEFAULT_ALLOWED_EXTENSION)) {
if (DEFAULT_ALLOWED_EXTENSION == IMAGE_EXTENSION) {
return DEFAULT_ALLOWED_EXTENSION + "--------" + extension + "--------" + ImgFileName;
} else if (DEFAULT_ALLOWED_EXTENSION == FLASH_EXTENSION) {
return DEFAULT_ALLOWED_EXTENSION + "--------" + extension + "--------" + ImgFileName;
} else if (DEFAULT_ALLOWED_EXTENSION == MEDIA_EXTENSION) {
return DEFAULT_ALLOWED_EXTENSION + "--------" + extension + "--------" + ImgFileName;
} else {
return DEFAULT_ALLOWED_EXTENSION + "--------" + extension + "--------" + ImgFileName;
}
}
String fileName = "/" + DateFormatUtils.format(new Date(), "yyyy/MM/dd") + "/" + encodingFilename(ImgFileName) + "." + extension;
File desc = new File(fileDir.getAbsolutePath() + File.separator + fileName);
if (!desc.getParentFile().exists()) {
desc.getParentFile().mkdirs();
}
if (!desc.exists()) {
desc.createNewFile();
}
imgFile.transferTo(desc);
String pathFileName = fileDir + fileName;
if (StringUtils.contains(fileDir.getAbsolutePath(), ":")) {
pathFileName = StringUtils.substringAfterLast(fileDir.getAbsolutePath(), ":") + fileName;
}
pathFileName = pathFileName.replaceAll("\\\\", "/");
return pathFileName;
}
public static final boolean isAllowedExtension(String extension, String[] allowedExtension) {
for (String str : allowedExtension) {
if (str.equalsIgnoreCase(extension)) {
return true;
}
}
return false;
}
private static final String encodingFilename(String filename) {
filename = filename.replace("_", " ");
filename = DigestUtil.hmacSign(filename + System.nanoTime() + counter++);
return filename;
}
public static String Extension(String prefix) {
switch (prefix) {
case IMAGE_PNG:
return "png";
case IMAGE_JPG:
return "jpg";
case IMAGE_JPEG:
return "jpeg";
case IMAGE_BMP:
return "bmp";
case IMAGE_GIF:
return "gif";
default:
return "";
}
}
}
package com.zkc.student.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/student/**").addResourceLocations("file:/student/");
}
}
package com.zkc.student.utils;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Random;
public class DigestUtil {
private static String encodingCharset = "UTF-8";
public static String hmacSign(String aValue, int length) {
String md5Str = hmacSign(aValue);
if (md5Str.length() < length) {
length = md5Str.length();
}
return md5Str.substring(0, length);
}
public static String hmacSign(String aValue) {
return hmacSign(aValue, "zkc");
}
public static String hmacSign(String aValue, String aKey) {
byte k_ipad[] = new byte[64];
byte k_opad[] = new byte[64];
byte keyb[];
byte value[];
try {
keyb = aKey.getBytes(encodingCharset);
value = aValue.getBytes(encodingCharset);
} catch (UnsupportedEncodingException e) {
keyb = aKey.getBytes();
value = aValue.getBytes();
}
Arrays.fill(k_ipad, keyb.length, 64, (byte) 54);
Arrays.fill(k_opad, keyb.length, 64, (byte) 92);
for (int i = 0; i < keyb.length; i++) {
k_ipad[i] = (byte) (keyb[i] ^ 0x36);
k_opad[i] = (byte) (keyb[i] ^ 0x5c);
}
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
return null;
}
md.update(k_ipad);
md.update(value);
byte dg[] = md.digest();
md.reset();
md.update(k_opad);
md.update(dg, 0, 16);
dg = md.digest();
return toHex(dg);
}
public static int randomCode() {
return new Random().nextInt(9000) + 1000;
}
public static String toHex(byte input[]) {
if (input == null)
return null;
StringBuffer output = new StringBuffer(input.length * 2);
for (int i = 0; i < input.length; i++) {
int current = input[i] & 0xff;
if (current < 16)
output.append("0");
output.append(Integer.toString(current, 16));
}
return output.toString();
}
public static String getHmac(String[] args, String key) {
if (args == null || args.length == 0) {
return (null);
}
StringBuffer str = new StringBuffer();
for (int i = 0; i < args.length; i++) {
str.append(args[i]);
}
return (hmacSign(str.toString(), key));
}
public static String digest(String aValue) {
aValue = aValue.trim();
byte value[];
try {
value = aValue.getBytes(encodingCharset);
} catch (UnsupportedEncodingException e) {
value = aValue.getBytes();
}
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA1");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
return toHex(md.digest(value));
}
}
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
这里只是针对图片上传写的,稍加修改就可以上传其他文件