标签:src 后台 图片 cname err lstat files method ||
引入js
<script th:src="@{/js/ajaxfileupload.js}"></script>
html
<tr> <td>附件:</td> <td> <input type="hidden" id="insertcyefuji" name="fuji" /> <input type="file" id="uploadcyefuji" name="file" /> </td> </tr>
js代码-----选择完文件后自动上传
$(‘input[id="uploadcyefuji"]‘).change(function(e){
var formData = new FormData();
formData.append(‘file‘, $(‘#uploadcyefuji‘)[0].files[0]);
$.ajax({
url: ‘/fileUpload‘,
type: ‘POST‘,
cache: false,
data: formData,
processData: false,
contentType: false
}).done(function(res) {
alert("上传成功")
}).fail(function(res) {
alert("上传失败");
});
})
controller后台代码
1 /** 2 * 实现文件上传 3 * @throws IOException 4 * @throws IllegalStateException 5 * */ 6 @RequestMapping(value="fileUpload",method = RequestMethod.POST) 7 @ResponseBody 8 public String fileUpload(HttpServletRequest req,MultipartFile file) throws IllegalStateException, IOException{ 9 if(file.getOriginalFilename()==null||file.getOriginalFilename().equals("")){ 10 System.err.println("为空++++"); 11 return ""; 12 }else{ 13 String picName = UUID.randomUUID().toString(); 14 // 获取文件名 15 String oriName = file.getOriginalFilename(); 16 System.err.println(oriName+"图片名字"); 17 // 获取图片后缀 18 String extName = oriName.substring(oriName.lastIndexOf(".")); 19 System.err.println("后缀名字"+extName); 20 if(extName.equals(".jpg") || extName.equals(".JPG") ||extName.equals(".png") || extName.equals(".PNG")){ 21 String path = req.getSession().getServletContext().getRealPath("/"); 22 System.out.println("path="+path); 23 24 file.transferTo(new File(path+"upload/"+picName + extName)); 25 //user.setUsername(picName + extName); 26 //m.addAttribute("fileName"+count, picName + extName); 27 //count--; 28 //list.add(user); 29 30 // 设置图片名到商品中 31 System.err.println("上传图片完成"); 32 return "上传成功"; 33 }else { 34 System.err.println("格式不对"); 35 return "格式不对"; 36 37 } 38 } 39 }
springmvc_ajax异步上传文件(基于ajaxfileupload.js)
标签:src 后台 图片 cname err lstat files method ||
原文地址:https://www.cnblogs.com/chenlove/p/9450639.html