Springboot 上传图片功能

上传图片:

MyMvcConfig重写addResourceHandlers方法,判断jar包是windows还是linux系统下运行。

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    String os = System.getProperty("os.name");
    System.out.println(os);
    if(os.toLowerCase().startsWith("win")){
        //--------------------------------------windows下保存路径-------------------------------------------------------------
        //项目图片访问路径
        registry.addResourceHandler("/pictureUpload/project/**").addResourceLocations("file:D:/pictureUpload/project/");
    }else{
        //--------------------------------------linux下保存路径---------------------------------------------------------------------------------
        //项目图片访问路径
        registry.addResourceHandler("/pictureUpload/project/**").addResourceLocations("file:/root/pictureUpload/project/");
    }

}

Controller上传图片功能

 /**
     * 上传图片
     *
     * @param file
     * @return
     */
    @Transactional
    @ResponseBody
    @PostMapping("/backgallery/PictureUpload")
    public String Backgallery(@RequestParam(value = "projectImg", required = true) MultipartFile file,
                              HttpServletRequest request) {
        //将图片上传到服务器
        if (file.isEmpty()) {
            return "项目图片不能为空";
        }
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        //图片名称为uuid+图片后缀防止冲突
        String fileName = UUID.randomUUID().toString() + "." + suffix;
        String os = System.getProperty("os.name");
        //文件保存路径
        String filePath = "";
        if (os.toLowerCase().startsWith("win")) {
            //windows下的路径
            filePath = "d:/pictureUpload/project/";
        } else {
            //linux下的路径
            filePath = "/root/pictureUpload/project/";
        }
        try {
            //写入图片
            Boolean writePictureflag = FileUtils.uploadFile(file.getBytes(), filePath, fileName);
            if (writePictureflag == false) {
                //上传图片失败
                return "上传项目图片失败";
            } else {
                //上传成功后,将可以访问的完整路径返回
                String fullImgpath = "/pictureUpload/project/" + fileName;
                String jsonData = "{'data':{'src':'" + fullImgpath + "'}}";

                //获取当前登录对象
                User loginUser = (User) request.getSession().getAttribute("loginUser");

                //将图片信息传入数据库
                Gallery gallery = new Gallery();
                gallery.setGmtcreate(System.currentTimeMillis());
                gallery.setFullimgpath(fullImgpath);
                gallery.setUsername(loginUser.getName());
                galleryService.addGallery(gallery);

                return jsonData;
            }
        } catch (Exception e) {
            e.printStackTrace();
            //上传图片失败
            return "上传项目图片失败";
        }
    }

工具类:

/**
 * @description:文件操作相关工具类
 * @Author MRyan
 * @Date 2020/3/28 8:43
 * @Version 1.0
 */
public class FileUtils {

    public static Boolean uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        FileOutputStream out = null;
        try {
            File targetFile = new File(filePath);
            //如果目录不存在,创建目录
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            out = new FileOutputStream(filePath+fileName);
            out.write(file);
            out.flush();
            //写入成功
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            //写入失败
            return false;
        } finally {
            out.close();
        }
    }

}

接下来是html整合layUi

<div class="layui-form-item magt3">
            <div class="layui-upload">
                <button type="button" class="layui-btn layui-btn-normal" id="test1">选择图片</button>
                <button type="button" style="margin-left: 20px" class="layui-btn layui-btn-danger" id="btn">上传图片
                </button>
                <div class="layui-upload-list">
                    <img class="layui-upload-img" id="demo1">
                    <p id="demoText"></p>
                </div>
            </div>
        </div>

js:

<script>

    //一般直接写在一个js文件中
    layui.use(['layer', 'upload'], function () {
        var form = layui.form
            , upload = layui.upload;

        //图片上传
        var uploadInst = upload.render({
            elem: '#test1'
            , url: '/backgallery/PictureUpload'
            , method: 'post'  
            //多图上传,multiple: true
            , auto: false
            , bindAction: '#btn'
            , accept: 'images'
            , acceptMime: 'image/*'
            , field: 'projectImg'
            , choose: function (obj) {
                alert("选择成功,请点击上传");
            }
            , done: function (res) {
                //上传成功,获得图片地址
                $('#demo1').attr('src', res.data);
                console.log(res.data);
                alert("上传成功");
            }
            , error: function (res) {
                $('#demo1').attr('src', res.data);
                console.log(res.data);
                alert("上传成功");
                window.location.reload();
            }
        });

    });


</script>

Bug:

上传图片失败由于图片大小过大
解决方案:
在application-properties中配置

spring.servlet.multipart.max-file-size=50000000000
spring.servlet.multipart.max-request-size=200000000000

删除图片:

同理删除图片只需要定位到图片在服务器下的位置,然后File.delete()即可
Controller代码
/**
* 删除图片
*
* @param model
* @return
*/
@GetMapping("/backgallery/Delgallery/{id}")
public String DelBackgallery(@PathVariable(“id”) int id) {
String os = System.getProperty(“os.name”);
//根据id查询服务器图片地址 删除图片并且清除数据库记录
Gallery gallery = galleryService.qeryGalleryById(id);
String fullImgpath = null;
String filename = gallery.getFullimgpath().substring(gallery.getFullimgpath().lastIndexOf(’/’) + 1);
if (os.toLowerCase().startsWith(“win”)) {
//windows下的路径
fullImgpath = “d:/pictureUpload/project/”+filename;
} else {
//linux下的路径
fullImgpath = “/root/pictureUpload/project/”+filename;
}
if (gallery != null) {
boolean istrue = FileUtils.delFile(fullImgpath);
if (istrue) {
//删除数据库中图片信息
galleryService.delGallery(id);
}
}

    return "redirect:/backgallery";
}

FileUtils工具类

/**
     * 删除图片
     *
     * @param fullImgpath
     * @return
     */
    public static boolean delFile(String fullImgpath) {
        //fullImgpath 是"/pictureUpload/project/" + fileName;
        File file = new File(fullImgpath);
        //文件是否存在
        if (file.exists()) {
            if (file.delete()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_35416214/article/details/106231487
今日推荐