利用layui实现文件上传功能

利用layui实现文件上传功能

  1. 前端部分
<input class="btn-upload file-up" style="display: inline-block;" type="file" accept="image/*" multiple name="risenUpload" id="file3">上传</input>
 var uploadInst3 = upload.render({
            elem: '#file3' //绑定元素
            ,url: '${base}/public/upload/uploadFile.do'
            ,data:{
                'crfileType' : '04',
            }
            ,before: function(obj){ //obj参数包含的信息,跟 choose回调完全一致,可参见上文。
                obj.preview(function(index, file, result){
                    //  console.log(file); //得到文件对象
                    name=file.name;
                    size=file.size;
                });
            }
            ,done: function(res){
                // 附件回显js编写处
                console.log(res);
                risenfgForm = res.data.originalName;
                if(risenfgForm.length > 25){
                    risenfgForm = risenfgForm.substr(risenfgForm.length - 25);
                    $('#images4').html(risenfgForm);
                }else{
                    $('#images4').html(risenfgForm);
                }

                $('#images4').html(risenfgForm);
                $('#span4').show();
                var fileUuid4 = res.data.fileUuid;
                //给隐藏框的uuid赋值
                $("#fileUuid4").val(fileUuid4);
            }
            ,error: function(res){
                alert("上传接口出错");
                //  console.log(res);
            }
        });
  1. 后台调用接口
package com.risen.wechat.controller;

import com.risen.base.frame.controller.ExeMvcAction;
import com.risen.hp.fastjson.JSONObject;
import com.risen.resrc.model.CoreResrcFile;
import com.risen.resrc.service.ICoreResrcFileService;
import com.risen.wechat.unit.FetchPropertyUtil;
import com.risen.wechat.unit.ResponseTemplate;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @ClassName: RisenUploadMvcAction
 * @Description:
 * @Author:
 * @Date: 2019/10/18 16:43
 * @Version V1.0
 **/
@Controller
@RequestMapping("/public/upload")
public class RisenUploadMvcAction extends ExeMvcAction {

    @Autowired
    private ICoreResrcFileService coreResrcFileService;

    @RequestMapping("/uploadFile")
    @ResponseBody
    public JSONObject uploadFile(@RequestParam MultipartFile file,@Param(value = "crfileType")String crfileType){
        ResponseTemplate template = ResponseTemplate.createOk();
        Map<String,Object> fileData = new HashMap<String ,Object>();

        /** 上传逻辑 */
        String msg = "操作成功";
       // Properties properties = new Properties();
        try {
            // properties.load(new FileInputStream(new File(this.getClass().getResource("/").getPath()+ "/com/risen/wechat/config/view-extend-app.properties")));
           // String storePath = properties.getProperty("WeChat_File_Path");
            String storePath = FetchPropertyUtil.getProperty("WeChat_File_Path","/com/risen/wechat/config/view-extend-app.properties");
            /**  保存文件到磁盘*/
            String orginalName = file.getOriginalFilename();
            String storeFileName = orginalName.substring(0,orginalName.indexOf("."));
            String ext = orginalName.substring(orginalName.indexOf("."),orginalName.length());
            System.out.println("===========" + ext);
//            storeFileName += System.currentTimeMillis() + ext;
            storeFileName = System.currentTimeMillis() + ext;
//            storePath += storeFileName + ext;
            storePath += storeFileName ;
            file.transferTo(new File(storePath));
            /** 保存文件信息到数据库  */
            CoreResrcFile coreResrcFile = new CoreResrcFile();
            coreResrcFile.setCrfileOriginalName(file.getOriginalFilename());
            coreResrcFile.setCrfileName(storeFileName);
            coreResrcFile.setCrfileServerPath("/" + storeFileName);
            coreResrcFile.setCrfileContentType(file.getContentType());
            coreResrcFile.setExtension(ext);
            coreResrcFile.setCrfileSize(file.getSize());
            //附件类型(从上到下01,02,03,04)
            coreResrcFile.setCrfileType(crfileType);
            coreResrcFileService.save(coreResrcFile);
            fileData.put("fileUuid",coreResrcFile.getUuid());
            fileData.put("originalName",coreResrcFile.getOriginalFileName());
            fileData.put("serverPath",coreResrcFile.getCrfileServerPath());
            template.setResultData(fileData);
            } catch (Exception e) {
                msg = "文件保存失败";
                template.setSuccess(false);
                e.printStackTrace();
            }
        template.setMsgMetaRespMsg(msg);
        return template.getResultJson();
    }



}

  1. 涉及的返回数据通用工具类
package com.risen.wechat.unit;

import com.risen.hp.fastjson.JSONObject;
import org.springframework.http.HttpStatus;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * @ClassName: ResponseUtil
 * @Description: 自定义接口返回统一格式
 * @Author: fxb
 * @Date: 2019/9/1 15:39
 * @Version V1.0
 **/
public class ResponseTemplate {

    public static final String MSG_META = "meta";
    public static final String MSG_META_RESP_CODE = "respCode";
    public static final String MSG_META_RESP_MSG = "respMsg";
    public static final String MSG_META_SERVICE_CODE = "serviceCode";
    public static final String MSG_META_RESP_VER = "ver";
    public static final String MSG_META_RESP_VERSION = "01";
    public static final String RESULT_DATA = "data";
    public static final String SUCCESS = "success";

    /**
     *  定义返回结构存储为json
     *  */
    private JSONObject resultJson = new JSONObject();

    /**
     * 定义 状态信息存储集合
     * */
    private Map<String ,Object> meta = new LinkedHashMap<String ,Object>();

    /**
     *  定义 返回结构数据存储集合
     *  */
    private Object data = new LinkedList<Object>();

    /**
     * 外部静止实例化
     */
    protected ResponseTemplate() {

    }

    protected ResponseTemplate(HttpStatus status,boolean success) {
        init(status,success);
    }

    /**
     *  向外提供一个创建默认 请求成功的实例入口
     * @return ResponseUtil
     */
    public static ResponseTemplate createOk(){
        return new ResponseTemplate(HttpStatus.OK,true);
    }

    /**
     *  向外提供一个创建默认 请求失败的实例入口
     * @return ResponseUtil
     */
    public static ResponseTemplate createFail(){
        return new ResponseTemplate(HttpStatus.INTERNAL_SERVER_ERROR,false);
    }

    /**
     * 返回结构数据
     */
    public JSONObject getResultJson(){
       // resultJson.put(MSG_META,meta);
        resultJson.put(RESULT_DATA,data);
        return this.resultJson;
    }

    /**
     * 再返回实例前 先初始化一些内部数据
     * */
    private void init(HttpStatus status,boolean success){
        resultJson.put(MSG_META_RESP_CODE, String.valueOf(status.value()));
        resultJson.put(MSG_META_RESP_MSG,status);
        resultJson.put(MSG_META_SERVICE_CODE,"");
        resultJson.put(MSG_META_RESP_VER,MSG_META_RESP_VERSION);
        resultJson.put(SUCCESS,success);
    }

    public void setSuccess(boolean success){
        resultJson.put(SUCCESS,success);
    }

    public void setServerError(String value){
        resultJson.put(MSG_META_RESP_CODE,String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR));
        resultJson.put(MSG_META_RESP_MSG,String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase() + value));
    }

    public void setBadRequest(String value){
        resultJson.put(MSG_META_RESP_CODE,String.valueOf(HttpStatus.BAD_REQUEST));
        resultJson.put(MSG_META_RESP_MSG,String.valueOf(HttpStatus.BAD_REQUEST.getReasonPhrase() + value));
    }

    public void setMsgMetaRespCode(String value){
        resultJson.put(MSG_META_RESP_CODE, value);
    }
    public String getMsgMetaRespCode(String value){
        return (String) resultJson.get(MSG_META_RESP_CODE);
    }

    public void setMsgMetaRespMsg(String value){
        resultJson.put(MSG_META_RESP_MSG,value);
    }
    public String getMsgMetaRespMsg(){
        return  (String) resultJson.get(MSG_META_RESP_MSG);
    }

    public void setMsgMetaServiceCode(String value){
        resultJson.put(MSG_META_SERVICE_CODE,value);
    }
    public String getMsgMetaServiceCode(){
        return (String) resultJson.get(MSG_META_SERVICE_CODE);
    }

    public void setMsgMetaRespVer(String value){
        resultJson.put(MSG_META_RESP_VER,value);
    }
    public String getMsgMetaRespVer(){
        return (String) resultJson.get(MSG_META_RESP_VER);
    }

    public void setResultData(Object valueData){
        this.data = valueData;
    }
    public Object getResultData(){
        return this.data;
    }

}

  1. properties常量工具类
package com.risen.wechat.unit;

import com.risen.hp.sfw.util.Assert;

import java.io.FileInputStream;
import java.util.Properties;

/**
 * @ClassName: FetchPropertyUtil
 * @Description: 获取properties常量工具类
 * @Author:
 * @Date: 2019/10/21 9:43
 * @Version V1.0
 **/
public class FetchPropertyUtil {

    private static Properties properties = new Properties();


    private FetchPropertyUtil() {
    }

    /**
     * 通过key获取 配置文件中的值
     * @param key
     */
    public static String getProperty(String key,String propertiesFilePath) throws Exception {
        loadProperties(propertiesFilePath);
        Assert.hasLength(key);
        return properties.getProperty(key);
    }

    /**
     * 加载properties文件
     * @param propertiesFilePath properties文件的相对路径
     */
    private static Properties loadProperties(String propertiesFilePath) throws Exception {
        Assert.hasLength(propertiesFilePath);
        if (!propertiesFilePath.startsWith("/")){
            throw new Exception("propertiesFilePath must be startWith the letter of / ");
        }
        properties.load(new FileInputStream(FetchPropertyUtil.class.getResource("/").getPath()+ propertiesFilePath));
        return properties;
    }


}

  1. 配置文件设置:微信端 上传文件 保存路径前缀
#微信端 上传文件 保存路径前缀
WeChat_File_Path=D:/RESOURCE_ROOT/ATTATCHMENT/
发布了33 篇原创文章 · 获赞 2 · 访问量 4740

猜你喜欢

转载自blog.csdn.net/qq_36778310/article/details/102909295