eclipse
layui首先html引入layui模板,js及css,如图
搭建Springboot+thymeleaf情况,成立文件夹static/upload,作为文件上传后的路径
参考如图所示html,class引入layui-upload
代码:
*图片
选择文件
单文件书写js代码(主动上传auto:true,不主动上传auto:false):
//选完文件后主动上传
upload.render({
elem: '#showimage'
,url: '/a_product/upload'
,auto: true
,field:"file1"
});
单文件后端java代码:
@ResponseBody
@RequestMapping("upload")
public Map upload(MultipartFile file1) throws FileNotFoundException {
UploadUtil.singFile(file1,GetTimestamp.getRandomTime(),"static/upload/");
Map map=new HashMap<>();
map.put("code", 0);
return map;
}
UploadUtil文件上传东西类代码:
public class UploadUtil {
public static String singFile(MultipartFile file,String fileName,String folder) throws FileNotFoundException {
//利用ResourceUtils 来获取真实路径 确保摆设时不会犯错
File path = new File(ResourceUtils.getURL("classpath:").getPath());
System.out.println(path.getAbsolutePath());
//若是上传的文件为/static/upload/ 如下
File upload = new File(path.getAbsolutePath(), folder);
if (!upload.exists())
upload.mkdirs();
String uploadPath = upload + "\\";
System.out.println("图片上传后的路径:"+uploadPath);
try {
File fileUpload=new File(uploadPath + fileName + ".jpg");
file.transferTo(fileUpload);
return "/"+folder+fileName+".jpg";
} catch (IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "error";
}
}
具体操作演示界面如下:
节制台找到文件上传后的路径
按照上传之后的目次查看,上传之后结果图如下
0 篇文章
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!