layui提供了简单的前端上传图片的案例,但很少有后端案例,返回时必须是json的格式并且有code参数layui的接口才不会报异常
package com.action;
import cn.hutool.json.JSONObject;
import com.mysql.jdbc.CharsetMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Controller
public class UpLoadAction {
File tempPathFile;
private String uploadPath = System.getProperty("ROOT") + "/tmp"; // 上传文件的目录
@RequestMapping("/upload")
@ResponseBody
public JSONObject uploadImage(@RequestParam("file") MultipartFile file) {
JSONObject res = new JSONObject();
JSONObject resUrl = new JSONObject();
if (!file.isEmpty()) {
Map<String, String> resObj = new HashMap<>(CharsetMapping.MAP_SIZE);
try {
//得到旧文件名
String oldFileName =file.getOriginalFilename();
//得到后缀名
int index =oldFileName.lastIndexOf(".");
String extName =oldFileName.substring(index);
//新文件名
String newFileName=System.nanoTime()+extName;
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(new File(uploadPath, newFileName)));
out.write(file.getBytes());
out.flush();
out.close();
} catch (IOException e) {
res.put("code", 1);
res.put("msg", "上传出错");
res.put("data", resUrl);
return res;
}
res.put("code", 0);
res.put("msg", "上传成功");
res.put("data", resUrl);
return res;
} else {
res.put("code", 0);
res.put("msg", "上传为空");
res.put("data", resUrl);
return res;
}
}
}
System.nanoTime()方法获取当前时间,以微毫秒为单位
java的UrlDcode解码方式
URLEncode和URLDecode用于完成普通字符串和 application/x-www-from-urlencoded MIME字符串之间的相互转化
如果传递的字符串中包含非西欧字符的字符串,会被转化成%XX%XX XX为十六进制的数字
try {
// 将application/x-www-from-urlencoded字符串转换成普通字符串
String keyWord = URLDecoder.decode("%C4%E3%BA%C3", "GBK");
System.out.println(keyWord); //输出你好
// 将普通字符创转换成application/x-www-from-urlencoded字符串
String urlString = URLEncoder.encode("你好", "GBK"); //输出%C4%E3%BA%C3
System.out.println(urlString);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}