上传图片,使用很简单的办法上传图片

使用很简单的办法上传图片

1. 首先把上传的页面写好

<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>使用很简单的办法上传图片</title>
<head th:include="include::header">
    <link rel="shortcut icon" href="favicon.ico">
    <link href="/css/bootstrap.min.css?v=3.3.6" rel="stylesheet">
    <link href="/css/font-awesome.css?v=4.4.0" rel="stylesheet">
    <link href="/css/animate.css" rel="stylesheet">
    <link href="/css/style.css?v=4.1.0" rel="stylesheet">
</head>
<style>
    h3{
        color: #000023;
        display: block;
        line-height: 26px;
        text-align: left;
    }
    h4{
        color: #3b0000;
        margin-left: 8px;
    }
    .fist{
        background-color: #b9bebb;
        height: 26px;
    }
    .set-status{
        margin-left: 66px;
        margin-top: 10px;
    }
    .ps{
        color: #272727;
        font-family: "楷体";
        font-size: 16px;
    }
</style>
<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox float-e-margins">
                <div class="ibox-content">
                    <form method="POST" enctype="multipart/form-data"  id="signupForm" >
                        <!--获取到xMainHome的id   方便前后台的数据传输-->
                        <input id="id" type="hidden" name="id" th:value="${wxMainHD.id}">
                        <div class="fist-picture">
                            <div class="fist" >
                                <h3>首页图</h3>
                            </div>

                            <label class="fist-show" style="margin-top: 6px">
                                <h4> 首页展示图(请点击黑色线框中选择需要上传的图片):</h4>
                            </label>
                            <!--首页展示图片上传框-->
                            <div class="form-group">
                                <!--设置图片上传类型以及函数触发事件-->
                                <input accept=".jpg,.jpeg,.png" type="file" class="files" id="mainLogoHome" name="mainLogo" style="display:none;" onchange="fileChange(event)">
                                <div  class="picture" style="margin-left: 40px;border:1px solid #000">
                                    <!--显示首页图片区域-->
                                    <img th:src="${wxMainHD.mainLogo}"  id="img-change" width="600px" height="350px"><br>
                                    <span style="color:grey;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;">图片仅支持JPG/JPEG/PNG格式,大小不超过2M</span>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="save-content" style="margin-left: 130px;margin-top: 10px">
                                <button id="b1" type="submit" class="btn btn-primary" >上传图片</button>&nbsp;
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

</div>
<div th:include="include::footer"></div>
<script type="text/javascript" src="/js/jquery-labelauty.js"></script>
<script type="text/javascript" src="/js/wangEditor.js"></script>
<script type="text/javascript" src="/js/appjs/sys/WxMainHome/editIn.js"></script>
</body>
</html>

JS:

/**
 * 设置默认规则
 */
$(function () {
    validateRule();
})
var data=[];

/**
 * 设定默认规则
 */
$.validator.setDefaults({
    submitHandler : function() {
        if($('#img-change').attr("src").length==0){
            alert("请上传首页图mainLogo!");
        }else{
            $('#b1').attr("disabled","true");
            saveEditIn();
        }
    }
});

/**
 * 设定单击事件(首页)
 */
$("#img-change").click(function () {
    $("#mainLogoHome").click();
});

/**
 * 单击图片区域选定需要上传的图片(首页)
 * @param event
 * @returns {boolean}
 */
var fileChange = function (event) {
    var files = event.target.files, file;
    if (files && files.length > 0) {
        // 获取目前上传的文件
        file = files[0];
        // 文件大小校验的动作
        if (file.size > 1024 * 1024 * 2) {
            alert('图片大小不能超过2MB!');
            return false;
        }
        // 获取 window 的 URL 工具
        var URL = window.URL || window.webkitURL;
        // 通过 file 生成目标 url
        var imgURL = URL.createObjectURL(file);
        // 用attr将img的src属性改成获得的url
        $("#img-change").attr("src", imgURL);
    }
};

/**
 * 保存编辑的内页
 */
var saveEditIn = function () {
    layer.load(1,{
        shade: [0.5,"#6a6a6a"]
    })
    var formData = new FormData();
    // 将id值传进来
    var id = $("#id").val();
    var homeId = $("#homeId").val();
    var imgDetail = editor.txt.html();
    var status = $('input:radio[name="status"]:checked').val();

    // 打印出相应字段
    console.log(imgDetail)
    console.log(status)

    // 与首页相关
    console.log(document.getElementById("mainLogoHome").files[0]);
    if(document.getElementById("mainLogoHome").files[0]==="undefined"||document.getElementById("mainLogoHome").files[0]==null){
        formData.append("mainLogo",$("#img-change").attr("src"));
    } else {
        formData.append("file",document.getElementById("mainLogoHome").files[0],"mainLogo"+suffix($("#mainLogoHome").val()));
    }

    // 追加需要使用到的字段
    // 追加首页的d
    formData.append("id",id);
    // 追加详情页的homeId
    formData.append("homeId",homeId);
    // 追加详情页的imageUrl
    formData.append("imageUrl",imgDetail);
    // 追加首页的status
    formData.append("status",status);

    /**
     * AJAX请求---> POST
     */
    $.ajax({
        type:"POST",
        data:formData,
        url:"/sys/WxMainHome/saveEditIn",
        async : false,
        processData:false,
        contentType: false,
        success : function(r) {
            if (r.code == 0) {
                parent.layer.msg("内页编辑成功");
                parent.reLoad();
                // 获取窗口索引
                var index = parent.layer.getFrameIndex(window.name);
                parent.layer.close(index);

            } else {
                parent.layer.msg(r.msg);
            }

        }
    })
}

/**
 *  首页
 * @param name
 * @returns {string}
 */
var suffix = function (name) {
    var index1=name.lastIndexOf(".");
    var index2=name.length;
    var suffix=name.substring(index1+1,index2);
    return "."+suffix;
}


2. 上传图片工具类util

上传 FileUtils,就是将图片保存到盘符当中,

package com.ultrapower.life.admin.util;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;

public class FileUtils {
    // /上传
    public static String save(String dir, MultipartFile file) {
        if (file.isEmpty()) {
            return null;
        }
        String fileName = getPicRandomName(file.getOriginalFilename());
        File upload = getFileDir(dir);

        File dest = new File(upload,fileName);

        try {
            file.transferTo(dest);
            return Constant.imageUrl + dir+"/" + fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String getPicRandomName(String picName) {
        String name = "";
        String randomName = RandomValues.getRandoms(16);
        int index = picName.lastIndexOf(".");
        if(index<0)
            return randomName+".png";
        String picType = picName.substring(index);
        name = randomName + picType;
        return name;
    }
    public static File getFileDir(String id) {
        String childPath="/";
        String filePath = Constant.imageFilePath;
        if (StringUtils.isNotBlank(id)){
            childPath = id+"/";
        }
        //如果上传目录为/static/images/upload/,则可以如下获取
        File upload=new File(filePath,childPath);
        if(!upload.exists()){
            upload.mkdirs();
        }
        System.out.println(upload.getAbsolutePath());
        return upload;
    }

}

保存图片时随机生成文件名

RandomValues

package com.ultrapower.life.admin.util;

/**
 * 生成指定位数随机数
 * Created by wuyongchang on 2019/10/30 14:07
 */
public class RandomValues {
    private static String[] randomValues = new String[]{"0","1","2","3","4","5","6","7","8","9","_","a", "b", "c", "d", "e", "f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
    private static String[] randomValuesNumber = new String[]{"0","1","2","3","4","5","6","7","8","9"};

    public static String getRandoms(int lenght) {
        StringBuffer str = new StringBuffer();
        for(int i = 0;i < lenght; i++){
            Double number=Math.random()*(randomValues.length-1);
            str.append(randomValues[number.intValue()]);
        }
        return str.toString();
    }

    public static String getRandomsNumber(int lenght) {
        StringBuffer str = new StringBuffer();
        for(int i = 0;i < lenght; i++){
            Double number=Math.random()*(randomValuesNumber.length-1);
            str.append(randomValuesNumber[number.intValue()]);
        }
        return str.toString();
    }
}

图片信息

ImgInfo

package com.ultrapower.life.admin.util;

import lombok.Data;

import java.util.Arrays;

@Data
public class ImgInfo {
    private Integer errno;
    private String[] data;
    @Override
    public String toString() {
        return "ImgInfo [errno=" + errno + ", data=" + Arrays.toString(data) + "]";
    }
}

3.controller层


/**
     * 编辑内页
     * @param model
     * @param id
     * @return
     */
    @Log("编辑内页")
    @RequiresPermissions("sys:WxMainHome:editIn")
    @GetMapping("/editIn/{id}")
    public String editIn(Model model, @PathVariable("id") Integer id){
        WxHomeDetailVO wxMainHD = wxMainHomeService.getId(id);
        model.addAttribute("wxMainHD",wxMainHD);
        return prefix + "/editIn";
    }

/**
     * 对编辑内页保存
     * @param file
     * @param wxMainHome
     * @param wxMainDetail
     * @return
     */
    @RequiresPermissions("sys:WxMainHome:editIn")
    @PostMapping("/saveEditIn")
    @ResponseBody
    public R saveEditIn(@RequestParam(value = "file",required = false) MultipartFile file, WxMainHome wxMainHome,
                        WxMainDetail wxMainDetail){
        // 保存(内页编辑)首页
        boolean flag = wxMainHomeService.saveInfo(file,wxMainHome);
        if (flag) {
            return R.ok();
        } else {
            return R.error("保存失败");
        }
    }

4. service及其实现类

service

    boolean saveInfo(MultipartFile files, WxMainHome wxMainHome);

service实现类

 /**
     * 保存首页图片
     * @param files
     * @param wxMainHome
     * @return
     */
    @Override
    @Transactional(rollbackFor=Exception.class)
    public boolean saveInfo(MultipartFile files, WxMainHome wxMainHome) {
        String mainLogo = "";
        // 上传图片名
        String originalFileName = "";
        if (files != null){
            try {
                // 生成新的文件名
                byte[] fileBytes =files.getBytes();
                // 取得当前文件名
                originalFileName = files.getOriginalFilename();
                // 生成文件名
                if (originalFileName.contains("mainLogo")){
                    String save = FileUtils.save(mainLogo,files);
                    wxMainHome.setMainLogo(save);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 保存图片后自动更新时间
        wxMainHome.setUpdateTime(LocalDateTime.now());
        boolean flag = wxMainHomeMapper.saveInfo(wxMainHome);
        return flag;
    }

5. mapper文件

(1)接口

    Boolean saveInfo(WxMainHome wxMainHome);

(2)xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ultrapower.life.mapper.WxMainHomeMapper">
    <resultMap id="ResultMap" type="WxMainHome">
      <id property="id" column="id"/>
        <result property="position" column="position"/>
        <result property="type" column="type"/>
        <result property="name" column="name"/>
        <result property="status" column="status"/>
        <result property="mainLogo" column="main_logo"/>
        <result property="createTime" column="create_time"/>
        <result property="updateTime" column="update_time"/>
    </resultMap>

    <!--将首页图地址更改-->
    <update id="saveInfo" parameterType="com.ultrapower.life.entity.WxMainHome">
        update wx_main_home
        set
        status=#{status},
        main_logo=#{mainLogo},
        update_time=#{updateTime}
        where id=#{id}
    </update>


</mapper>

由于我们需要将上传的图片放到盘符上,因此需要在

application-dev.yml文件里设置路径

上传图片,使用很简单的办法上传图片_第1张图片

这里设置好就可以了,还需要在本地搭建一个Nginx,方便开发
好了,我们来演示一下:
选择图片之前:

上传图片,使用很简单的办法上传图片_第2张图片

点击之后:

上传图片,使用很简单的办法上传图片_第3张图片

图片加载进来了:

上传图片,使用很简单的办法上传图片_第4张图片

保存之后:

上传图片,使用很简单的办法上传图片_第5张图片

OK 了!!!

你可能感兴趣的:(Java,图片上传)