layui文件上传接口后端具体实现SpringMVC

做课程设计时候,用到了layui文件上传接口,参考官方文档给出的响应接口文档:

{
 "code": 0
 ,"msg": ""
 ,"data": {
 "src": "http://cdn.layui.com/123.jpg"
 }
}

然后具体的上传书写方式分为前端和后端,layui官方并没有说明上传的接口文档,因此在网上查了一些资料,写出来总结一下:

前端:

var formData = new FormData();
	var url_userProfileUpdate='api/v1/idol/userProfileUpdate';
	layui.use('upload', function(){
		  var upload = layui.upload;
		  //执行实例
		  var uploadInst = upload.render({
		    elem: '#test1' //绑定元素
		    ,url: url_userProfileUpdate //上传接口
		    ,data:formData //可选项。额外的参数,如:{id: 123, abc: 'xxx'}
		    ,before: function(obj){
		        //预读本地文件示例,不支持ie8
		        obj.preview(function(index, file, result){
		          $('#user_profile').attr('src', result); //图片链接(base64)
		        });
		      }
		    ,done: function(res){
		    	alert(res.msg);
		    }
		    ,error: function(){
		      //请求异常回调
		    }
		  });
		});

后端:

@ResponseBody
	@RequestMapping(value="userProfileUpdate",method = RequestMethod.POST)
	public String userProfileUpdate(@RequestParam("file")MultipartFile file,HttpServletRequest request,HttpServletResponse response) throws Exception
	{
		 JSONObject res = new JSONObject();
         JSONObject resUrl = new JSONObject();
		if(UserAuth.authUser(request))
		{
		 String username=UserAuth.getUsername(request);
         //上传文件路径 
         String path =request.getSession().getServletContext().getRealPath("imgs")+"\\";
         System.out.println("文件名称"+file.getOriginalFilename()); 
         //上传文件名         
         String name = file.getOriginalFilename();//上传文件的真实名称
         String suffixName = name.substring(name.lastIndexOf("."));//获取后缀名
         String hash = Integer.toHexString(new Random().nextInt());//自定义随机数(字母+数字)作为文件名
         String fileName = hash + suffixName;  
         HashMap<String,String> profile=new HashMap<String,String>();
//         userService
         profile.put("username", username);
         profile.put("profile", fileName);
         boolean userProfileUpdate = userService.userProfileUpdate(profile);
         if(userProfileUpdate)
         {
         File filepath = new File(path, fileName); 
        // System.out.println("随机数文件名称"+filepath.getName()); 
         //判断路径是否存在,没有就创建一个 
         if (!filepath.getParentFile().exists()) { 
             filepath.getParentFile().mkdirs(); 
             } 
         //将上传文件保存到一个目标文档中 
         File tempFile = new File(path + fileName);
         file.transferTo(tempFile);
         
         resUrl.put("src", tempFile.getPath());
         res.put("code", 0);
         res.put("msg", "上传成功!");
         res.put("data", resUrl);
         //str = "{\"code\": 0,\"msg\": \"上传成功\",\"data\": {\"src\":\""+path+fileName + "\"}}";
        // System.out.println("res里面的值:");
         System.out.println(res.toString());    
         return res.toString();
         }
         else
         {
			 res.put("code", 0);
	         res.put("msg", "上传失败!");
	         res.put("data", null);
	         return res.toString();
         }
		}
		else
		{
			 res.put("code", 0);
	         res.put("msg", "上传失败!");
	         res.put("data", null);
	         return res.toString();
		}
	}
原创文章 42 获赞 72 访问量 8203

猜你喜欢

转载自blog.csdn.net/weixin_43249548/article/details/103682677