可以在前端用JavaScript将图片转为Base64 字符串的格式上传,也可以直接上传
package com.doing.uitls;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
public class UploadUtil {
public static String uploadFile(MultipartFile file, String path) throws IOException {
String name = file.getOriginalFilename();//上传文件的名字
String suffixName = name.substring(name.lastIndexOf("."));//文件的后缀
String hash = Integer.toHexString(new Random().nextInt());//自定义随机数,字母加数字为文件名
String fileName = hash + suffixName;
boolean b = fileName.matches("^[0-9a-zA-Z_-]*(\\.png||.jpg|.jpeg|.bmp)$");
if (b) {
File tempFile = new File(path, fileName);
if (!tempFile.getParentFile().exists()) {
tempFile.getParentFile().mkdirs();
}
if (tempFile.exists()) {
tempFile.delete();
}
tempFile.createNewFile();
file.transferTo(tempFile);
return tempFile.getName();
}
return "null";
}
public static void deleteFile(String filePath) throws Exception {
File file = new File(filePath);
if (!file.exists()) return;
if (file.isFile()) {
file.delete();
} else {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
String root = files[i].getAbsolutePath();// 得到子文件或文件夹的绝对路径
// System.out.println(root);
deleteFile(root);
}
}
}
public static void moveFile(String fileName, String destinationFloderPath) {
File file = new File(fileName);
File destFloder = new File(destinationFloderPath);
//检查目标路径是否合法
if (destFloder.exists()) {
if (destFloder.isFile())
throw new RuntimeException("目标路径是个文件,请检查目标路径!");
} else {
if (!destFloder.mkdirs())
throw new RuntimeException("目标文件夹不存在,创建失败!");
}
//检查源文件是否合法
if (file.isFile() && file.exists()) {
String destinationFile = destinationFloderPath + "/" + file.getName();
if (!file.renameTo(new File(destinationFile))) {
throw new RuntimeException("移动文件失败!");
}
} else {
throw new RuntimeException("要备份的文件路径不正确,移动失败!");
}
}
}
package com.doing.uitls;
import java.util.Random;
/**
* 各种id生成策略
* Title: IDUtils
* Description:
* @author 无名
* @date 2018年3月26日下午2:32:10
* @version 1.0
*/
public class IDUtils {
/**
* 图片名生成
*/
public static String genImageName() {
//取当前时间的长整形值包含毫秒
long millis = System.currentTimeMillis();
//long millis = System.nanoTime();
//加上三位随机数
Random random = new Random();
int end3 = random.nextInt(999);
//如果不足三位前面补0
String str = millis + String.format("%03d", end3);
return str;
}
/**
* 商品id生成
*/
public static long genNewsId() {
//取当前时间的长整形值包含毫秒
long millis = System.currentTimeMillis();
//long millis = System.nanoTime();
//加上两位随机数
Random random = new Random();
int end2 = random.nextInt(99);
//如果不足两位前面补0
String str = millis + String.format("%02d", end2);
long id = new Long(str);
return id;
}
}
<div style="width: 100px;height: 50px;">
<form action="/upload/image" id="form-change-avatar" method="POST" enctype="multipart/form-data">
<p>请选择上传的文件</p>
<p><input type="file" name="file" required="required" multiple="multiple"></p>
<p><input type="submit" style="color: red" value="上传"/></p>
</form>
</div>
如果是将图片已经转成base64 的字符串了就直接用字符串接收
Ret 就是json类
@RequestMapping("image")
@ResponseBody
public Ret imageFile(@RequestParam("file") MultipartFile[] files){
Appuser user=new Appuser();
user.setUserid("77a1fed2-dfa2-4964-9654-8be59ed363da");
user.setUsername("wl");
for (int i = 0; i <files.length ; i++) {
Ret ret= imageUpLoadService.upLoadImage(files[i],user);
if(ret.isFail()){
return ret;
}
}
return Ret.ok();
}
private String applyUploadPath="E://sydata/imageUpLoad";
public Ret upLoadImage(MultipartFile file, Appuser user) {
if(file==null||file.getSize()==0){
return Ret.fail("msg","请选择图片");
}
String year_month = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String uuid = UUID.randomUUID().toString().replaceAll("-", "").trim();
String pathUrl = String.format("/%s/%s_imageName_%s.jpg", year_month, uuid, String.valueOf(Math.random()).substring(2, 8));
try {
//推荐使用spring自带API FileUtils.writeByteArrayToFile(new File(String.format("%s%s", applyUploadPath, pathFile)),file.getBytes());
Uitls.saveImage(file, String.format("%s%s", applyUploadPath, pathUrl));
// Uitls.base64toFile(Base64Image, String.format("%s%s", applyUploadPath, pathUrl));
} catch (Exception e) {
return Ret.fail("msg", "文件存储错误!" + e.getMessage());
}
Upload upload=new Upload();
upload.setServiceid(user.getUserid());
upload.setState(0);
List<Upload> list=uploadMapper.select(upload);
int size;
if(list==null){
size=1;
}else{
size=list.size()+1;
}
Upload filedata = new Upload();
filedata.setServiceid(user.getUserid());
filedata.setPathfile(pathUrl);
filedata.setFilename("test"+size);
Integer rows = uploadMapper.insertSelective(filedata);
if (rows != 1) {
try {
Utils.deleteFile(String.format("%s%s", applyUploadPath, pathUrl));
return Ret.fail("msg", "图片保存失败,遇到未知问题,请重新上传");
} catch (Exception e1) {
return Ret.fail("msg", "旧文件删除失败:" + e1.getMessage());
}
}
return Ret.ok();
}
public static String saveImage(MultipartFile file, String targetPath) throws IOException {
if (file.getSize() != 0) {
File dir = new File(targetPath);
if (!dir.exists()) {
dir.mkdirs();
}
//MultipartFile自带的解析方法
file.transferTo(dir);
return targetPath;
}
return null;
}
public static void base64toFile(String base64Code, String targetPath) throws IOException {
FileOutputStream out = null;
try {
File tempFile = new File(targetPath);
if (!tempFile.getParentFile().exists()) {
tempFile.getParentFile().mkdirs();
}
if (tempFile.exists()) {
tempFile.delete();
}
byte[] buffer = base64Code.getBytes();
out = new FileOutputStream(targetPath);
out.write(buffer);
} finally {
if (out != null)
out.close();
}
}
public static void deleteFile(String filePath) throws Exception {
File file = new File(filePath);
if (!file.exists()) return;
if (file.isFile()) {
file.delete();
} else {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
String root = files[i].getAbsolutePath();// 得到子文件或文件夹的绝对路径
// System.out.println(root);
deleteFile(root);
}
}
}
public class StringToBASE64MultipartFile implements MultipartFile {
private final byte[] imgContent;
private final String header;
public StringToBASE64MultipartFile(byte[] imgContent, String header) {
this.imgContent = imgContent;
this.header = header.split(";")[0];
}
@Override
public String getName() {
return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
}
@Override
public String getOriginalFilename() {
return System.currentTimeMillis() + (int)Math.random() * 10000 + "." + header.split("/")[1];
}
@Override
public String getContentType() {
return header.split(":")[1];
}
@Override
public boolean isEmpty() {
return imgContent == null || imgContent.length ==0;
}
@Override
public long getSize() {
return imgContent.length;
}
@Override
public byte[] getBytes() throws IOException {
return imgContent;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(imgContent);
}
@Override
public void transferTo(File file) throws IOException, IllegalStateException {
new FileOutputStream(file).write(imgContent);
}
}
public static MultipartFile base64MutipartFile(String imgStr){
try {
String [] baseStr = imgStr.split(",");
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] b = new byte[0];
b = base64Decoder.decodeBuffer(baseStr[1]);
/* String str= ImgaeDiscern.sample(b);//调用图片识别模板
if(str==null){//TODO 此处验证模板是否符合要求
return null;
}*/
for(int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
return new StringToBASE64MultipartFile(b,baseStr[0]) ;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
需要得到"APP_ID",“API_KEY”,“SECRET_KEY”,"templateSign"这四个值自己填入数组对应的参数内即可,最好在配置文件中直接读取方便维护
final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ImgaeDiscern.class);
public static String sample(byte[] b) throws IOException {
String[]arr={"APP_ID","API_KEY","SECRET_KEY","templateSign"};
String[] result= GetProperties.getConfig("ftpimages/iocrConfig.properties",arr);
if(result==null){
return null;
}
AipOcr client = new AipOcr(result[0], result[1], result[2]);
// 传入可选参数调用接口
HashMap<String, String> options = new HashMap<String, String>();
options.put("templateSign", result[3]);
// 参数为本地路径
try {
/* JSONObject res = client.custom(image,"templateSign" ,options);*/
JSONObject res = client.custom(b,"templateSign" ,options);
JSONObject data = (JSONObject) res.get("data");
JSONArray jsonArray= (JSONArray) data.get("ret");
for (int i = 0; i <jsonArray.length() ; i++) {
JSONObject jsonObject= (JSONObject) jsonArray.get(i);
Set<Map.Entry<String, Object>> entryMap=jsonObject.toMap().entrySet();
for (Map.Entry<String, Object> e: entryMap) {
/* if("word_name".equals(e.getKey())||"word".equals(e.getKey())){
logger.debug(e.getValue()+" ");
}*/
/*if("word".equals(e.getKey())){
logger.debug(e.getValue()+"");
}*/
if(StringHelper.isNull(e.getKey())||e.getValue()==null||"".equals(e.getValue())){
logger.error("照片字迹不清楚");
throw new RuntimeException("请按提示要求拍摄上传");
}
}
}
return "文件正常";
}catch (Exception e){
logger.error("遇到未知错误,请重新上传"+e.getMessage()+" : "+e.getClass().getName());
return null;
}
}