layui(1.0.9)文件上传upload,前后端代码

因为公司还在使用老版本的layui,文件上传在新版本中全部重写了,这里记录下老版本layui的文件上传。

前端代码:(引入layui相关包)

<input type="file" lay-type="file" id="xxxxx" name="file" class="layui-upload-file">

这里可以参考layui官方文档,有一点需要注意,name属性是必需的,当你选择好文件后,name属性的值,会在后台被相应的参数接收

如果你只写了上面的代码,会发现文件上传的按钮消失了。这很正常,因为框架就是这么设计的。

layui.upload({
  url: '/pay_channel/upload'
  ,before: function(input){
    //返回的参数item,即为当前的input DOM对象
    $(input).after('<input type="hidden" name="mchId-file" value="11111"/>');
    //layer.msg('文件上传中',{zIndex:20180509});
  }
  ,success: function(res){
  if(res.code == 'success'){
  layer.msg(res.message,{zIndex:20180510});
  certLocalPath = res.filePath
  }else{
  layer.msg(res.message,{zIndex:20180510});
  }
  }

});

url是请求地址,必须是AJAX请求(POST),必须返回JSON,返回的数据在success中操作,以上代码简单易懂,不用照抄。

before是指在上传请求进行之前,进行的一些操作,$(input).after('<input type="hidden" name="mchId-file" value="'+mchIdxx+'"/>');这段代码是为了追加一个参数,参数名字位mchId-file,值为11111,所以后端接收会有两个参数,file和mchId-file。

后端代码:

    @RequestMapping("/upload")
    @ResponseBody
    public String importFile(MultipartFile file, HttpServletRequest request) {
    JSONObject object = new JSONObject();
            try {
            String mchId = request.getParameter("mchId-file");
            String originalFilename = file.getOriginalFilename();
//            String dirPath = System.getProperty("user.dir")+"/wx";
//            String dirPath = this.getClass().getClassLoader().getResource("").getPath()+"wx";
            String dirPath = "/xxxx/java/pay/wx/cert";
            _log.info("证书上传的文件目录{}", dirPath);
            String filePath = "/"+mchId+"_"+originalFilename;
boolean b = new File(dirPath).mkdirs();
file.transferTo(new File(dirPath + filePath).getAbsoluteFile());

object.put("filePath", filePath);
object.put("code", "success");
object.put("message", "文件上传成功");
} catch (IOException e) {
e.printStackTrace();
object.put("code", "fail");
object.put("message", "文件上传失败");
}
            return object.toJSONString();

    }

获得的file是MultipartFile类对象,org.springframework.web.multipart.MultipartFile

该对象可以获取文件名字getOriginalFilename,获取文件流getInputStream,传输到另一个文件的方法transferTo等。

以上后端方法是将获取到的文件,保存到另一个特别目录中去。

再说几句题外话:

String dirPath = System.getProperty("user.dir");//获取项目地址根目录,就是说你workspace中,该项目初始目录。

String dirPath = this.getClass().getClassLoader().getResource("").getPath();//获取项目resource目录位置,即springboot中application.yml所在文件夹。

再windows中其实不需要写盘符来表示这个目录的绝对路径,String dirPath = "/xxxx/java/pay/wx/cert";如果你项目在D盘,那绝对路径就会变成D:/xxxx/java/pay/wx/cert,这样就避免了服务器windows与linux的问题。

但有一点要注意:File file = new File(dirPath + filePath).getAbsoluteFile(),如果使用/开头,需要用getAbsoluteFile()获取到D:/xxxx/java/pay/wx/cert路径的文件对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值