前言
提示:这里可以添加本文要记录的大概内容:
记录java一个综合借鉴学习使用的一种简单图片上传方法,按年月日自动创建上传文件夹,其中使用了layui模板,springboot框架
提示:以下是本篇文章正文内容,下面案例可供参考
一、图片上传类UploadFileUtilImg
代码如下(示例):
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
public class UploadFileUtilImg {
/*
* 上传图片文件服务器路径
*/
//private static final String return_path = "https://www.xy.com";
/*
* 上传图片文件本地路径
*/
private static final String return_path = "";
public Map<String,Object> UploadFileUtilLayui(@RequestParam("layuiFile") MultipartFile[] layuiFile, HttpServletRequest request,
HttpServletResponse response,String uploadFolder,String urlWeb,String xh){
//System.out.println("layuiFile=" + layuiFile);
// 本地使用
String rootPath = uploadFolder+ "yybm/photo/";
//返回路径
String fileUrl = return_path + urlWeb + "yybm/photo/";
//System.out.println("rootPath=" + rootPath);
//System.out.println("fileUrl=" + fileUrl);
//定义允许上传的文件扩展名
HashMap<String, String> extMap = new HashMap<String, String>();
extMap.put("image", "jpg,jpeg,png");
//最大文件大小 2*1024*1024 = 2M
long maxSize = 2097152;
response.setContentType("text/html; charset=UTF-8");
if(!ServletFileUpload.isMultipartContent(request)){
return getError("请选择文件。");
}
//检查目录
File uploadDir = new File(rootPath);
if(!uploadDir.exists()){
uploadDir.mkdir();
//return getError("上传目录不存在。");
}
//检查目录写权限
if(!uploadDir.canWrite()){
return getError("上传目录没有写权限。");
}
String dirName = request.getParameter("dir");
if (dirName == null) {
dirName = "image";
}
if(!extMap.containsKey(dirName)){
return getError("目录名不正确。");
}
//创建文件夹
//创建文件夹
rootPath += dirName + "/";
fileUrl += dirName + "/";
File saveDirFile = new File(rootPath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
// 创建年月文件夹
Calendar date = Calendar.getInstance();
rootPath += date.get(Calendar.YEAR) + "/" + (date.get(Calendar.MONTH) + 1) + "/";
fileUrl += date.get(Calendar.YEAR) + "/" + (date.get(Calendar.MONTH) + 1) + "/";
File dirFile = new File(rootPath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
String url[] = new String[layuiFile.length];
Map<String,Object> map = new HashMap<String, Object>();
for (int i=0;i<layuiFile.length;i++) {
//System.out.println(layuiFile[i]);
// 获取上传文件的名字
String fileName = layuiFile[i].getOriginalFilename();
// 获取长度
long fileSize = layuiFile[i].getSize();
//System.out.println("fileSize=" + fileSize);
if(!layuiFile[i].isEmpty()){
// 检查文件大小
if(layuiFile[i].getSize() > maxSize){
return getError("上传文件大小超过限制。");
}
// 检查扩展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
return getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");
}
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
//String newFileName = xh + "_" + df.format(new Date()) +"." + fileExt;
String newFileName = xh +"." + fileExt;
//监测是否存在同名文件,有就删除
String img_path = rootPath + newFileName;
File file = new File(img_path);
if (file.exists()) {//文件是否存在
file.delete();//存在就删了,返回1
}
try{
// 保存文件
//System.out.println(rootPath + newFileName);
FileCopyUtils.copy(layuiFile[i].getInputStream(), new FileOutputStream(rootPath + newFileName));
}catch(Exception e){
return getError("上传文件失败。");
}
url[i] = fileUrl + newFileName;
//map.put("code", 0);
//map.put("url", saveUrl + newFileName);
//return map;
}
}
map.put("code", 200);
map.put("url", url);
return map;
//return getError("服务器端错误。");
}
private Map<String,Object> getError(String message) {
Map<String,Object> map = new HashMap<String, Object>();
map.put("code", 101);
map.put("message", message);
return map;
}
}
二、使用方法
代码如下(示例):
1.后端controller调用方法
/**
* @Title: uploadImg
* @Description: TODO(上传图片)
*/
@RequestMapping(“uploadimg”)
@ResponseBody
public JSONObject uploadImg(@RequestParam(“layuiImg”) MultipartFile[] layuiFile, HttpServletRequest request, HttpServletResponse response){
String xh = request.getParameter("xh");
System.out.println("imgxh=" + xh);
String xm = request.getParameter("xm");
System.out.println("layuiFile=" + layuiFile);
Map<String,Object> map=new HashMap<>();
UploadFileUtilImg uploadFileUtilImg = new UploadFileUtilImg();
JSONObject result = new JSONObject();
map = uploadFileUtilImg.UploadFileUtilLayui(layuiFile, request, response,uploadFolder,urlWeb,xh);
String error = map.get("code").toString();
if("101".equals(error)){
result.put("code", 101);
result.put("msg", map.get("message"));
return result;
}
String url[]=(String[])map.get("url");
result.put("data", url[0]);
result.put("code", 200);
result.put("msg", "上传成功!");
String urlsc = url[0];
// 接收证件号
String card = request.getSession().getAttribute("account").toString();
// 保存照片结果
JSONObject result2 = yybmPhotoService.insertPhotoInfoByWeb(xm, xh, card, urlsc);
//接收并解析JSONObject
int code = Integer.parseInt(result2.getString("code"));
if(code == 200) {
result.put("msg", "上传并保存成功!");
}else {
result.put("msg", "上传成功,保存失败!");
}
return result;
}
2.前段页面使用方法
<script>
layui.use([ 'layer', 'form' ,'upload'], function() {// >=layui
var $ = layui.jquery;
var layer = layui.layer;
var form = layui.form;
var upload = layui.upload;
//获取需要上传照片的学号
var xm=$("#xm").val();
var xh=$("#xh").val();
var sign = $("#sign").val();;
//上传图片
var uploadInst=upload.render({
elem: '#uploadImg'
,url: '/upload/uploadimg?xh='+xh+'&xm='+xm
,field:"layuiImg"
,data:{"dir":"image"}
,accept: 'images' //只允许上传图片
,acceptMime: 'image/*' //只筛选图片
,size: 1024*2 //限定大小
,before: function(obj) {
//console.log(obj);
layer.msg('上传中...', {
icon: 16,
shade: 0.01,
time: 0
})
}
,done: function(res){
if(res.code==200){
$("#imgShow").attr("src",res.data);
layer.msg(res.msg,{
icon:6,
time:1000
},function(){
//window.location.reload();
});
}
if(res.code==101){
layer.msg(res.msg);
}
}
,error:function () {
}
});
})
</script>