Spring Boot+LayUi实现单文件上传

十点数据 1年前 ⋅ 3027 阅读

相关阅读:

X-admin2.2打开页面(添加弹窗),执行成功后如何关闭弹出窗口和刷新table表格内容?

基于X-admin2.2的后台管理系统登录实现

LayUi的动态表格table中设置下拉框Select编辑器

LayUi搜索时,如何只刷新表格内容,其他内容不变?

ZTree工具类汇总,包括:新增、编辑和删除节点,并提交后台

LayUi的Table表格defaultToolbar工具栏的显示与隐藏(权限控制)

前端代码如下:

<div class="layui-upload">
    <button style="margin-left: 40%;" class="layui-btn" id="test1"
        type="button">上传图片</button>
    <div class="layui-upload-list" style="width: 100px; height: 100px;">
        <img class="layui-upload-img" id="demo1"
            style="width: 200px; height: 125px; margin-left: 100%;">
        <p id="demoText"></p>
    </div>
    <input type="hidden" id="userId" value="${userId}">
</div>

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

        //普通图片上传
        var uploadInst = upload.render({
            elem : '#test1',
            url : '/layui/user/uploadImages' //改成您自己的上传接口
            ,
            before : function(obj) {
                //预读本地文件示例,不支持ie8
                obj.preview(function(index, file, result) {
                    $('#demo1').attr('src', result); //图片链接(base64)
                });
            },
            done : function(res) {
                console.log(res);
                message = res['sucess'];//后台返回的提示信息;
                if (res['sucess'] == "true" || res['sucess'] == true) {
                    layer.alert("上传成功", {
                        icon : 6,
                        time : 1000
                    }, function() {
                        //关闭当前frame
                        xadmin.close();
                    });
                } else {
                    return layer.msg('上传失败');
                }
            },
            error : function() {
                return layer.msg('上传失败');
            }
        });
    });

后端代码:

Controller

@RequestMapping(value = "/uploadImages", method = RequestMethod.POST)
public void uploadImages(ModelMap model, MultipartFile file, HttpServletRequest request,
		HttpServletResponse response) throws Exception {
	Map<String, String> result = new HashMap<String, String>();
	try {
		User user = getProfile();
		String path = WebUpload.uploads(file, request, response);
		result.put("sucess", "true");
		result.put("path", path);
		user.setAvatar(path);
		userService.save(user);
	} catch (Exception e) {
		result.put("sucess", "false");
	}
	writeJSON(response, JSONObject.fromObject(result).toString());
}

文件处理类(WebUpload):

package com.tdata.bplatform.utils;

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

public class WebUpload {
    private static String suffixStrs = "pcd|dxf|ufo|eps|ai|raw|WMF|bmp|jpg|png|tiff|gif|pcx|tga|exif|fpx|svg|psd|cdr";

    public static String uploads(MultipartFile file, 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("上传文件格式不正确!!");
            } else {
                String filepath = Consts.headPortrait + "/" + DateUtil.getYM_Not();
                File destfile = new File(uploadPath + filepath);
                if (!destfile.exists()) {
                    destfile.mkdirs();
                }
                // 新文件名称;
                String fileNameNew = DateUtil.getYMDHMSs_Not() + "." + suffix;
                File f = new File(System.getProperty("user.dir") + filepath + "/" + fileNameNew);
                if (!f.getParentFile().exists()) {
                    f.getParentFile().mkdirs();
                }
                if (f.exists()) {
                    f.delete();
                }
                file.transferTo(f);
                f.createNewFile();
                return filepath + "/" + fileNameNew;
            }
        } catch (Exception e) {
            throw e;
        }
    }
}

全部评论: 0

    我有话说: