layui + SSM 实现文件上传,前端+后端代码

layui + SSM 实现文件上传,前端+后端代码

html代码:

<div class="layui-upload">
  <button type="button" class="layui-btn" id="test1">上传图片button>
  <div class="layui-upload-list">
    <img class="layui-upload-img" id="demo1">
    <p id="demoText">p>
  div>
div>  

js代码:

<script>
    layui.use('upload', function(){
     
        var $ = layui.jquery
            ,upload = layui.upload;

  //普通文件上传
  var uploadInst = upload.render({
     
    elem: '#test1'
    ,url: '/crm/customer/upload.action'
    ,before: function(obj){
     
      //预读本地文件示例,不支持ie8
      obj.preview(function(index, file, result){
     
        $('#demo1').attr('src', result); //图片链接(base64)
      });
    }
    ,done: function(res){
     
      //如果上传失败
      if(res.code > 0){
     
        return layer.msg('上传失败');
      }
      //上传成功
    }
    ,error: function(){
     
      //演示失败状态,并实现重传
      var demoText = $('#demoText');
      demoText.html('上传失败 重试');
      demoText.find('.demo-reload').on('click', function(){
     
        uploadInst.upload();
      });
    }
  });
    });
</script>

spring-mvc.xml (很重要)


 	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
 		
 		<property name="maxUploadSize">
 			<value>10485760value>
 		property>
 		
 		<property name="defaultEncoding">
 			<value>UTF-8value>			
 		property> 
 	bean>

java后端接口:

	//资源上传
	@RequestMapping(value="upload",method=RequestMethod.POST,produces="application/json;charset=utf-8")
	@ResponseBody//json交互注解
	public Map<String, Object> uploadResource(HttpServletRequest request,HttpServletResponse response,HttpSession session,MultipartFile file) throws Exception{
     
		//UserExtend teacher = (UserExtend) session.getAttribute("userInfo");
		//String path = session.getServletContext().getRealPath("\\resource\\"+teacher.getUserCode());//这样只会保存到项目的文件目录下
        String path = "E:\\"+"001.png";
		String fileName = file.getOriginalFilename();  
        File dir = new File(path,fileName);        
        if(!dir.exists()){
     
            dir.mkdirs();
        }
        //MultipartFile自带的解析方法
        file.transferTo(dir);
        //upload要求返回的数据格式
        Map<String, Object> uploadData = new HashMap<String, Object>();
        Map<String, Object> data = new HashMap<String, Object>();
		//JSONArray data = JSONArray.fromObject(dir.getPath());
		uploadData.put("code", "0");
		uploadData.put("msg", "");
        //将文件路径返回
		data.put("src", dir.getPath());
		uploadData.put("data", data);
		//uploadData.put("data", "{\'src\':\'"+dir.getPath()+"\'}");      
        return uploadData;
        /* 返回接口格式
	          "code": 0
	          ,"msg": ""
	          ,"data": {
	           "src": "http://cdn.layui.com/123.jpg"
	          }
	    */   
	}

演示图片

layui + SSM 实现文件上传,前端+后端代码_第1张图片

你可能感兴趣的:(js,jsp,java)