layui刷新当前页面_使用LayUI进行文件上传(带预览功能)

1、添加LayUI上传组件需要的js文件

jquery.min.js、layui.all.js、layer.js

2、导入上传组件jar包

commons-fileupload、commons-io

3、在spring配置文件中限制上传文件的大小,否则会报错

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    <property name="maxUploadSize" value="1048576" />bean>

4、jsp页面代码

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

5、js代码

<script type="text/javascript">    //图片上传    layui.use('upload', function(){        var $ = layui.jquery            ,upload = layui.upload;        //普通图片上传        var uploadInst = upload.render({            elem: '#test1'            ,url: '/uploadImages'            ,before: function(obj){                //预读本地文件示例,不支持ie8                obj.preview(function(index, file, result){                                      $('#previewImg').attr('src', result); //图片链接(base64)                });            }            ,done: function(res){                //上传失败                if(res.code > 0){                    return layer.msg('上传失败');                }                //上传成功,返回的路径:res.filePath            }            ,error: function(){                //上传失败                return layer.msg('上传失败,请重试!');            }        });    });script>

6、后台java代码及工具类

/** * 文件上传 * @param file * @param request * @param response * @return * @throws Exception */@RequestMapping(value = "/uploadImages",method=RequestMethod.POST)@ResponseBodypublic WebUploadResult uploadImages(MultipartFile file,HttpServletRequest request, HttpServletResponse response) throws Exception {    String destDir = "/upload/picture";    WebUploadResult webResult = new WebUploadResult();    try {        String path = WebUpload.uploads(file, destDir, request,response);        webResult.setStatus(0);        webResult.setFilePath(path);    } catch (Exception e) {        e.printStackTrace();    }    return webResult;}

WebUpload.java类:

import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.File;import java.text.SimpleDateFormat;import java.util.Date;public class WebUpload {    private static String suffixStrs = "bmp|jpg|png|tiff|gif|pcx|tga|exif|fpx|svg|psd|cdr|pcd|dxf|ufo|eps|ai|raw|WMF";    public static String uploads(MultipartFile file, String destDir, HttpServletRequest request,                                 HttpServletResponse response) throws Exception {        //获取文件上传的真实路径        String uploadPath = request.getSession().getServletContext().getRealPath("/");        try {            //判断上传文件的后缀            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);            if (suffixStrs.indexOf(suffix) == -1) {                throw new Exception("上传文件格式不正确");            }            //保存文件的路径            String filepath = destDir + File.separator + createNewDir();            File destfile = new File(uploadPath + filepath);            if (!destfile.exists()) {                destfile.mkdirs();            }            //文件新名称            String fileNameNew = getFileNameNew() + "." + suffix;            File f = new File(destfile.getAbsoluteFile() + File.separator + fileNameNew);            if (f.exists()) {                return filepath + File.separator + fileNameNew;            }            file.transferTo(f);            f.createNewFile();            return filepath + File.separator + fileNameNew;        } catch (Exception e) {            throw e;        }    }    /**     * 为文件重新命名,命名规则为当前系统时间毫秒数     *     * @return string     */    private static String getFileNameNew() {        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");        return fmt.format(new Date());    }    /*    *以当前日期为名,创建新文件夹    @return    */    private static String createNewDir() {        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");        return fmt.format(new Date());    }}

WebUploadResult.java类:

/** * 默认的页面请求返回的model对象.用来包裹controller的页面输出 */public class WebUploadResult {    private int status;    private String filePath;    private WebUploadError error;    private String id;    public int getStatus() {        return status;    }    public void setStatus(int status) {        this.status = status;    }    public String getFilePath() {        return filePath;    }    public void setFilePath(String filePath) {        this.filePath = filePath;    }    public WebUploadError getError() {        return error;    }    public void setError(WebUploadError error) {        this.error = error;    }    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }}

WebUploadError.java类:

/** * 默认的页面请求返回的model对象.用来包裹controller的页面输出 */public class WebUploadError {   private int code;   private String message;   public int getCode() {      return code;   }   public void setCode(int code) {      this.code = code;   }   public String getMessage() {      return message;   }   public void setMessage(String message) {      this.message = message;   }}

注意:

在普通文件上传中,我们都是用

type="file" name="file">

这样来控制上传的。在LayUI上传组件中,实际上也是用这种方式来实现的。

60ce13b75e1e13658b6f9fbb2905eeba.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值