附源码:javaweb实现文件上传(dropZone插件+文件上传工具类)

46 篇文章 2 订阅
21 篇文章 1 订阅

最近有时间,就整理整理自己做过的项目~这是某学院的信息档案系统网页开发项目里的文件上传业务。
话不多说,进入正题

效果图:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
记得先引入dropZone相关js/css。

前端:
html

<div class="form-group">
   <label class="col-sm-3 control-label "></label>
   <div class="col-sm-8">
      <input type="hidden" id="dataId" name="dataId">
      <div id="dropz" class="dropzone"></div>
      </div>
</div>

js

//初始化文件上传框
  $(function () {
    Dropzone.autoDiscover = false;//防止报"Dropzone already attached."的错误
    var myDropzone = new Dropzone("#dropz", {
      url: rootPath + "/FileController/upload",//文件提交地址
      method: "post",  //也可用put
      paramName: "file", //默认为file
      maxFiles: 1,//一次性上传的文件数量上限
      maxFilesize: 100, //文件大小,单位:MB
      acceptedFiles: ".jpg,.gif,.png,.jpeg,.log,.rar,.zip,.gz,.7z,.txt,.docx,.doc", //上传的类型
      addRemoveLinks: true,
      parallelUploads: 1,//一次上传的文件数量
      //previewsContainer:"#preview",//上传图片的预览窗口
      dictDefaultMessage: '拖动文件至此或者点击上传',
      dictMaxFilesExceeded: "您最多只能上传1个文件!",
      dictResponseError: '文件上传失败!',
      dictInvalidFileType: "文件类型只能是图片格式、压缩包或*.log,*.txt。",
      dictFallbackMessage: "浏览器不受支持",
      dictFileTooBig: "文件过大上传文件最大支持.",
      dictRemoveFile: "删除",
      dictCancelUpload: "取消",
      init: function () {
        this.on("addedfile", function (file) {
          //上传文件时触发的事件
          //不是图片格式则预览指定文件图片
          if (!file.type.match(/image.*/)) {
            myDropzone.emit("thumbnail", file, rootPath + "/static/images/admin/file.png");
          }
        });
        this.on("success", function (file, data) {
          //上传成功触发的事件
          if (data != null && data != "") {
            $("#dataId").val(data.data);
          }

        });
        this.on("error", function (file, data) {
          //上传失败触发的事件

        });
        this.on("removedfile", function (file) {//删除文件触发结果
          let enable = file.previewElement.classList.contains("dz-error");
          if (!enable) {
            $("#dataId").val("");
          }
        });
      }
    });

  });

后台:
controller

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    @ApiOperation(value = "上传文件", notes = "上传文件")
    @ResponseBody
    public AjaxResult updateFile(@RequestParam("file") MultipartFile file) {
        try {
            if (!file.isEmpty()) {
                //插入文件存储表
                Integer id = sysDatasService.insertSelective(file);
                if (id != null) {
                    return success();
                }
            }
            return error();
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

service

/**
    * 文件上传文件存储到文件表
    *
    * @param file
    * @return 主键
    * @throws IOException
    */
   public Integer insertSelective(MultipartFile file) throws Exception {
       //文件上传获取文件名字(关于这个工具类,已上传至github:)
       String files = FileUploadUtils.upload(file, getFileAddress());
       //补充完整文件保存url地址
       String filesURL = "xxx";

       TsysDatas record = new TsysDatas();
       record.setFilePath(filesURL);
       if (tsysDatasMapper.insertSelective(record) > 0) {
           return record.getId();
       }
       return null;
   }

   /**
    * 获取系统文件存放地址(判断服务器类型,获得对应的字典参数,并根据该参数获得预设的储存地址)
    */
   private String getFileAddress() throws Exception {
       //获取服务器系统类型
       String systemName = System.getProperty("os.name").toLowerCase();
       //win系统
       if (systemName.contains("windows")) {
           try {
               return sysKvSettingService.getValueByDicKey("winFile");
           } catch (Exception e) {
               throw new Exception("字典参数-winFile不存在");
           }
       } else {
           try {
               return sysKvSettingService.getValueByDicKey("linuxFile");
           } catch (Exception e) {
               throw new Exception("字典参数-linuxFile不存在");
           }
       }
   }

pojo

package model;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;

@ApiModel(value = "TsysDatas对象", description = "文件存放信息")
public class TsysDatas implements Serializable {

    @ApiModelProperty(value = "id", required = true, position = 1, example = "1")
    private Integer id;

    @ApiModelProperty(value = "文件存放路径")
    private String filePath;

    private static final long serialVersionUID = 1L;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }
}

mapper

<insert id="insertSelective" parameterType="model.TsysDatas">
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into t_sys_datas
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="filePath != null">
        file_path,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="filePath != null">
        #{filePath,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>

工具类源码
链接:https://pan.baidu.com/s/1BVVVtvPxrhKMly0D7mFOIQ
提取码:1fsf

以上便是全部过程,有啥问题,欢迎留言!
觉得还不错可以点个赞哦~ 谢谢(๑•ᴗ•๑)

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值