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 篇文章
如果覺得我的文章對您有用,請隨意打賞。你的支持將鼓勵我繼續創作!