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

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

效果图:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
记得先引入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;
   }

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

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

发布了52 篇原创文章 · 获赞 84 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_39380155/article/details/104840431