• 若依 springBoot2.5 +vue2前后端分离,实现图片上传及下载功能。


    1. 图片上传

    1. vue 前端,引入< image-upload />组件。
    <el-row>
       <el-col :span="12">
         <el-form-item label="头像" prop="avatar">
           <image-upload v-model="form.avatar" :limit="1"/>
         </el-form-item>
       </el-col>
     </el-row>
    

    < image-upload />组件 源码:

    <template>
      <div class="component-upload-image">
        <el-upload
          :action="uploadImgUrl"
          list-type="picture-card"
          :on-success="handleUploadSuccess"
          :before-upload="handleBeforeUpload"
          :limit="limit"
          :on-error="handleUploadError"
          :on-exceed="handleExceed"
          ref="imageUpload"
          :on-remove="handleDelete"
          :show-file-list="true"
          :headers="headers"
          :file-list="fileList"
          :on-preview="handlePictureCardPreview"
          :class="{hide: this.fileList.length >= this.limit}"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
    
        <!-- 上传提示 -->
        <div class="el-upload__tip" slot="tip" v-if="showTip">
          请上传
          <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
          <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
          像素为 <b style="color: #f56c6c">320 x 320 </b>
          的文件
        </div>
    
        <el-dialog
          :visible.sync="dialogVisible"
          title="预览"
          width="800"
          append-to-body
        >
          <img
            :src="dialogImageUrl"
            style="display: block; max-width: 100%; margin: 0 auto"
          />
        </el-dialog>
      </div>
    </template>
    
    <script>
    import { getToken } from "@/utils/auth";
    import {globalConfig} from "../../../public/config";
    export default {
      props: {
        value: [String, Object, Array],
        // 图片数量限制
        limit: {
          type: Number,
          default: 5,
        },
        // 大小限制(MB)
        fileSize: {
           type: Number,
          default: 5,
        },
        // 文件类型, 例如['png', 'jpg', 'jpeg']
        fileType: {
          type: Array,
          default: () => ["png", "jpg", "jpeg"],
        },
        // 是否显示提示
        isShowTip: {
          type: Boolean,
          default: true
        }
      },
      data() {
        return {
          number: 0,
          uploadList: [],
          dialogImageUrl: "",
          dialogVisible: false,
          hideUpload: false,
          baseUrl: process.env.NODE_ENV === "production" ? globalConfig.reqUrl:process.env.VUE_APP_BASE_API,
          uploadImgUrl: (process.env.NODE_ENV === "production" ? globalConfig.reqUrl:process.env.VUE_APP_BASE_API) + "/common/upload", // 上传的图片服务器地址
          headers: {
            Authorization: "Bearer " + getToken(),
          },
          fileList: []
        };
      },
      watch: {
        value: {
          handler(val) {
            if (val) {
              // 首先将值转为数组
              const list = Array.isArray(val) ? val : this.value.split(',');
              // 然后将数组转为对象数组
              this.fileList = list.map(item => {
                if (typeof item === "string") {
                  if (item.indexOf(this.baseUrl) === -1) {
                      item = { name: this.baseUrl + item, url: this.baseUrl + item };
                  } else {
                      item = { name: item, url: item };
                  }
                }
                return item;
              });
            } else {
              this.fileList = [];
              return [];
            }
          },
          deep: true,
          immediate: true
        }
      },
      computed: {
        // 是否显示提示
        showTip() {
          return this.isShowTip && (this.fileType || this.fileSize);
        },
      },
      methods: {
        // 上传前loading加载
        handleBeforeUpload(file) {
          let isImg = false;
          if (this.fileType.length) {
            let fileExtension = "";
            if (file.name.lastIndexOf(".") > -1) {
              fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
            }
            isImg = this.fileType.some(type => {
              if (file.type.indexOf(type) > -1) return true;
              if (fileExtension && fileExtension.indexOf(type) > -1) return true;
              return false;
            });
          } else {
            isImg = file.type.indexOf("image") > -1;
          }
    
          if (!isImg) {
            this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
            return false;
          }
          if (this.fileSize) {
            const isLt = file.size / 1024 / 1024 < this.fileSize;
            if (!isLt) {
              this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
              return false;
            }
          }
          this.$modal.loading("正在上传图片,请稍候...");
          this.number++;
        },
        // 文件个数超出
        handleExceed() {
          this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
        },
        // 上传成功回调
        handleUploadSuccess(res, file) {
          if (res.code === 200) {
            this.uploadList.push({ name: res.fileName, url: res.fileName });
            this.uploadedSuccessfully();
          } else {
            this.number--;
            this.$modal.closeLoading();
            this.$modal.msgError(res.msg);
            this.$refs.imageUpload.handleRemove(file);
            this.uploadedSuccessfully();
          }
        },
        // 删除图片
        handleDelete(file) {
          const findex = this.fileList.map(f => f.name).indexOf(file.name);
          if(findex > -1) {
            this.fileList.splice(findex, 1);
            this.$emit("input", this.listToString(this.fileList));
          }
        },
        // 上传失败
        handleUploadError() {
          this.$modal.msgError("上传图片失败,请重试");
          this.$modal.closeLoading();
        },
        // 上传结束处理
        uploadedSuccessfully() {
          if (this.number > 0 && this.uploadList.length === this.number) {
            this.fileList = this.fileList.concat(this.uploadList);
            this.uploadList = [];
            this.number = 0;
            this.$emit("input", this.listToString(this.fileList));
            this.$modal.closeLoading();
          }
        },
        // 预览
        handlePictureCardPreview(file) {
          this.dialogImageUrl = file.url;
          this.dialogVisible = true;
        },
        // 对象转成指定字符串分隔
        listToString(list, separator) {
          let strs = "";
          separator = separator || ",";
          for (let i in list) {
            if (list[i].url) {
              strs += list[i].url.replace(this.baseUrl, "") + separator;
            }
          }
          return strs != '' ? strs.substr(0, strs.length - 1) : '';
        }
      }
    };
    </script>
    <style scoped lang="scss">
    // .el-upload--picture-card 控制加号部分
    ::v-deep.hide .el-upload--picture-card {
        display: none;
    }
    // 去掉动画效果
    ::v-deep .el-list-enter-active,
    ::v-deep .el-list-leave-active {
        transition: all 0s;
    }
    
    ::v-deep .el-list-enter, .el-list-leave-active {
        opacity: 0;
        transform: translateY(0);
    }
    </style>
    
    
    
    
    
    1. 后台
      CommonController.java
     /**
         * 通用上传请求(单个)
         */
        @PostMapping("/upload")
        public AjaxResult uploadFile(MultipartFile file) throws Exception {
            try {
                // 上传文件路径
                String filePath = RuoYiConfig.getUploadPath();
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                AjaxResult ajax = AjaxResult.success();
                ajax.put("url", url);
                ajax.put("fileName", fileName);
                ajax.put("newFileName", FileUtils.getName(fileName));
                ajax.put("originalFilename", file.getOriginalFilename());
                return ajax;
            } catch (Exception e) {
                return AjaxResult.error(e.getMessage());
            }
        }
    

    FileUploadUtils.java

    package com.dechnic.common.utils.file;
    
    import com.dechnic.common.config.RuoYiConfig;
    import com.dechnic.common.constant.Constants;
    import com.dechnic.common.exception.file.FileNameLengthLimitExceededException;
    import com.dechnic.common.exception.file.FileSizeLimitExceededException;
    import com.dechnic.common.exception.file.InvalidExtensionException;
    import com.dechnic.common.utils.DateUtils;
    import com.dechnic.common.utils.StringUtils;
    import com.dechnic.common.utils.uuid.Seq;
    import org.apache.commons.io.FilenameUtils;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.File;
    import java.io.IOException;
    import java.nio.file.Paths;
    import java.util.Objects;
    
    /**
     * 文件上传工具类
     *
     * @author ruoyi
     */
    public class FileUploadUtils
    {
        /**
         * 默认大小 50M
         */
        public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;
    
        /**
         * 默认的文件名最大长度 100
         */
        public static final int DEFAULT_FILE_NAME_LENGTH = 100;
    
        /**
         * 默认上传的地址
         */
        private static String defaultBaseDir = RuoYiConfig.getProfile();
    
        public static void setDefaultBaseDir(String defaultBaseDir)
        {
            FileUploadUtils.defaultBaseDir = defaultBaseDir;
        }
    
        public static String getDefaultBaseDir()
        {
            return defaultBaseDir;
        }
    
        /**
         * 以默认配置进行文件上传
         *
         * @param file 上传的文件
         * @return 文件名称
         * @throws Exception
         */
        public static final String upload(MultipartFile file) throws IOException
        {
            try
            {
                return upload(getDefaultBaseDir(), file, com.dechnic.common.utils.file.MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
            }
            catch (Exception e)
            {
                throw new IOException(e.getMessage(), e);
            }
        }
    
        /**
         * 根据文件路径上传
         *
         * @param baseDir 相对应用的基目录
         * @param file 上传的文件
         * @return 文件名称
         * @throws IOException
         */
        public static final String upload(String baseDir, MultipartFile file) throws IOException
        {
            try
            {
                return upload(baseDir, file, com.dechnic.common.utils.file.MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
            }
            catch (Exception e)
            {
                throw new IOException(e.getMessage(), e);
            }
        }
    
        /**
         * 文件上传
         *
         * @param baseDir 相对应用的基目录
         * @param file 上传的文件
         * @param allowedExtension 上传文件类型
         * @return 返回上传成功的文件名
         * @throws FileSizeLimitExceededException 如果超出最大大小
         * @throws FileNameLengthLimitExceededException 文件名太长
         * @throws IOException 比如读写文件出错时
         * @throws InvalidExtensionException 文件校验异常
         */
        public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension)
                throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
                InvalidExtensionException
        {
            int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length();
            if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
            {
                throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
            }
    
            assertAllowed(file, allowedExtension);
    
            String fileName = extractFilename(file);
    
            String absPath = getAbsoluteFile(baseDir, fileName).getAbsolutePath();
            file.transferTo(Paths.get(absPath));
            return getPathFileName(baseDir, fileName);
        }
    
        /**
         * 编码文件名
         */
        public static final String extractFilename(MultipartFile file)
        {
            return StringUtils.format("{}/{}_{}.{}", DateUtils.datePath(),
                    FilenameUtils.getBaseName(file.getOriginalFilename()), Seq.getId(Seq.uploadSeqType), getExtension(file));
        }
    
        public static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException
        {
            File desc = new File(uploadDir + File.separator + fileName);
    
            if (!desc.exists())
            {
                if (!desc.getParentFile().exists())
                {
                    desc.getParentFile().mkdirs();
                }
            }
            return desc;
        }
    
        public static final String getPathFileName(String uploadDir, String fileName) throws IOException
        {
            int dirLastIndex = RuoYiConfig.getProfile().length() + 1;
            String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
            return Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName;
        }
    
        /**
         * 文件大小校验
         *
         * @param file 上传的文件
         * @return
         * @throws FileSizeLimitExceededException 如果超出最大大小
         * @throws InvalidExtensionException
         */
        public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
                throws FileSizeLimitExceededException, InvalidExtensionException
        {
            long size = file.getSize();
            if (size > DEFAULT_MAX_SIZE)
            {
                throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
            }
    
            String fileName = file.getOriginalFilename();
            String extension = getExtension(file);
            if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension))
            {
                if (allowedExtension == com.dechnic.common.utils.file.MimeTypeUtils.IMAGE_EXTENSION)
                {
                    throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,
                            fileName);
                }
                else if (allowedExtension == com.dechnic.common.utils.file.MimeTypeUtils.FLASH_EXTENSION)
                {
                    throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,
                            fileName);
                }
                else if (allowedExtension == com.dechnic.common.utils.file.MimeTypeUtils.MEDIA_EXTENSION)
                {
                    throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,
                            fileName);
                }
                else if (allowedExtension == com.dechnic.common.utils.file.MimeTypeUtils.VIDEO_EXTENSION)
                {
                    throw new InvalidExtensionException.InvalidVideoExtensionException(allowedExtension, extension,
                            fileName);
                }
                else
                {
                    throw new InvalidExtensionException(allowedExtension, extension, fileName);
                }
            }
        }
    
        /**
         * 判断MIME类型是否是允许的MIME类型
         *
         * @param extension
         * @param allowedExtension
         * @return
         */
        public static final boolean isAllowedExtension(String extension, String[] allowedExtension)
        {
            for (String str : allowedExtension)
            {
                if (str.equalsIgnoreCase(extension))
                {
                    return true;
                }
            }
            return false;
        }
    
        /**
         * 获取文件名的后缀
         *
         * @param file 表单文件
         * @return 后缀名
         */
        public static final String getExtension(MultipartFile file)
        {
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());
            if (StringUtils.isEmpty(extension))
            {
                extension = com.dechnic.common.utils.file.MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType()));
            }
            return extension;
        }
    }
    
    

    2.图片下载

    1. 前端vue2
     <el-table-column label="小程序二维码" align="center" prop="wchatQr" >
        <template slot-scope="scope">
          <el-link  @click="downloadQrImg(scope.row.wchatQr)" >
            <img
              :src="scope.row.wchatQr"
              style="display: block; max-width: 100%; margin: 0 auto"
            />
          </el-link>
        </template>
    
      </el-table-column>
    
      //下载小程序二维码
        downloadQrImg(qrUrl){
          console.log("qrUrl:"+qrUrl.substring(this.serverUrl.length,qrUrl.length));
          download.resource(qrUrl);
        }
    

    download.js

    import axios from 'axios'
    import { Message } from 'element-ui'
    import { saveAs } from 'file-saver'
    import { getToken } from '@/utils/auth'
    import errorCode from '@/utils/errorCode'
    import { blobValidate } from "@/utils/ruoyi";
    import {globalConfig} from "../../public/config";
    
    const baseURL = process.env.NODE_ENV === "production" ?globalConfig.reqUrl : process.env.VUE_APP_BASE_API
    
    export default {
      name(name, isDelete = true) {
        var url = baseURL + "/common/download?fileName=" + encodeURI(name) + "&delete=" + isDelete
        axios({
          method: 'get',
          url: url,
          responseType: 'blob',
          headers: { 'Authorization': 'Bearer ' + getToken() }
        }).then(async (res) => {
          const isLogin = await blobValidate(res.data);
          if (isLogin) {
            const blob = new Blob([res.data])
            this.saveAs(blob, decodeURI(res.headers['download-filename']))
          } else {
            this.printErrMsg(res.data);
          }
        })
      },
      resource(resource) {
        var url = baseURL + "/common/download/resource?resource=" + encodeURI(resource);
        axios({
          method: 'get',
          url: url,
          responseType: 'blob',
          headers: { 'Authorization': 'Bearer ' + getToken() }
        }).then(async (res) => {
          const isLogin = await blobValidate(res.data);
          if (isLogin) {
            const blob = new Blob([res.data])
            this.saveAs(blob, decodeURI(res.headers['download-filename']))
          } else {
            this.printErrMsg(res.data);
          }
        })
      },
      zip(url, name) {
        var url = baseURL + url
        axios({
          method: 'get',
          url: url,
          responseType: 'blob',
          headers: { 'Authorization': 'Bearer ' + getToken() }
        }).then(async (res) => {
          const isLogin = await blobValidate(res.data);
          if (isLogin) {
            const blob = new Blob([res.data], { type: 'application/zip' })
            this.saveAs(blob, name)
          } else {
            this.printErrMsg(res.data);
          }
        })
      },
      saveAs(text, name, opts) {
        saveAs(text, name, opts);
      },
      async printErrMsg(data) {
        const resText = await data.text();
        const rspObj = JSON.parse(resText);
        const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
        Message.error(errMsg);
      }
    }
    
    
    
    1. 后端代码
      CommonController.java
    import axios from 'axios'
    import { Message } from 'element-ui'
    import { saveAs } from 'file-saver'
    import { getToken } from '@/utils/auth'
    import errorCode from '@/utils/errorCode'
    import { blobValidate } from "@/utils/ruoyi";
    import {globalConfig} from "../../public/config";
    
    const baseURL = process.env.NODE_ENV === "production" ?globalConfig.reqUrl : process.env.VUE_APP_BASE_API
    
    export default {
      name(name, isDelete = true) {
        var url = baseURL + "/common/download?fileName=" + encodeURI(name) + "&delete=" + isDelete
        axios({
          method: 'get',
          url: url,
          responseType: 'blob',
          headers: { 'Authorization': 'Bearer ' + getToken() }
        }).then(async (res) => {
          const isLogin = await blobValidate(res.data);
          if (isLogin) {
            const blob = new Blob([res.data])
            this.saveAs(blob, decodeURI(res.headers['download-filename']))
          } else {
            this.printErrMsg(res.data);
          }
        })
      },
      resource(resource) {
        var url = baseURL + "/common/download/resource?resource=" + encodeURI(resource);
        axios({
          method: 'get',
          url: url,
          responseType: 'blob',
          headers: { 'Authorization': 'Bearer ' + getToken() }
        }).then(async (res) => {
          const isLogin = await blobValidate(res.data);
          if (isLogin) {
            const blob = new Blob([res.data])
            this.saveAs(blob, decodeURI(res.headers['download-filename']))
          } else {
            this.printErrMsg(res.data);
          }
        })
      },
      zip(url, name) {
        var url = baseURL + url
        axios({
          method: 'get',
          url: url,
          responseType: 'blob',
          headers: { 'Authorization': 'Bearer ' + getToken() }
        }).then(async (res) => {
          const isLogin = await blobValidate(res.data);
          if (isLogin) {
            const blob = new Blob([res.data], { type: 'application/zip' })
            this.saveAs(blob, name)
          } else {
            this.printErrMsg(res.data);
          }
        })
      },
      saveAs(text, name, opts) {
        saveAs(text, name, opts);
      },
      async printErrMsg(data) {
        const resText = await data.text();
        const rspObj = JSON.parse(resText);
        const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
        Message.error(errMsg);
      }
    }
    
    
    

    FileUtils.java

    package com.dechnic.common.utils.file;
    
    import com.dechnic.common.config.RuoYiConfig;
    import com.dechnic.common.utils.DateUtils;
    import com.dechnic.common.utils.StringUtils;
    import com.dechnic.common.utils.uuid.IdUtils;
    import org.apache.commons.io.FilenameUtils;
    import org.apache.commons.io.IOUtils;
    import org.apache.commons.lang3.ArrayUtils;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import java.net.URLEncoder;
    import java.nio.charset.StandardCharsets;
    
    /**
     * 文件处理工具类
     *
     * @author ruoyi
     */
    public class FileUtils
    {
        public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";
    
        /**
         * 输出指定文件的byte数组
         *
         * @param filePath 文件路径
         * @param os 输出流
         * @return
         */
        public static void writeBytes(String filePath, OutputStream os) throws IOException
        {
            FileInputStream fis = null;
            try
            {
                File file = new File(filePath);
                if (!file.exists())
                {
                    throw new FileNotFoundException(filePath);
                }
                fis = new FileInputStream(file);
                byte[] b = new byte[1024];
                int length;
                while ((length = fis.read(b)) > 0)
                {
                    os.write(b, 0, length);
                }
            }
            catch (IOException e)
            {
                throw e;
            }
            finally
            {
                IOUtils.close(os);
                IOUtils.close(fis);
            }
        }
    
        /**
         * 写数据到文件中
         *
         * @param data 数据
         * @return 目标文件
         * @throws IOException IO异常
         */
        public static String writeImportBytes(byte[] data) throws IOException
        {
            return writeBytes(data, RuoYiConfig.getImportPath());
        }
    
        /**
         * 写数据到文件中
         *
         * @param data 数据
         * @param uploadDir 目标文件
         * @return 目标文件
         * @throws IOException IO异常
         */
        public static String writeBytes(byte[] data, String uploadDir) throws IOException
        {
            FileOutputStream fos = null;
            String pathName = "";
            try
            {
                String extension = getFileExtendName(data);
                pathName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension;
                File file = com.dechnic.common.utils.file.FileUploadUtils.getAbsoluteFile(uploadDir, pathName);
                fos = new FileOutputStream(file);
                fos.write(data);
            }
            finally
            {
                IOUtils.close(fos);
            }
            return com.dechnic.common.utils.file.FileUploadUtils.getPathFileName(uploadDir, pathName);
        }
    
        /**
         * 删除文件
         *
         * @param filePath 文件
         * @return
         */
        public static boolean deleteFile(String filePath)
        {
            boolean flag = false;
            File file = new File(filePath);
            // 路径为文件且不为空则进行删除
            if (file.isFile() && file.exists())
            {
                file.delete();
                flag = true;
            }
            return flag;
        }
    
        /**
         * 文件名称验证
         *
         * @param filename 文件名称
         * @return true 正常 false 非法
         */
        public static boolean isValidFilename(String filename)
        {
            return filename.matches(FILENAME_PATTERN);
        }
    
        /**
         * 检查文件是否可下载
         *
         * @param resource 需要下载的文件
         * @return true 正常 false 非法
         */
        public static boolean checkAllowDownload(String resource)
        {
            // 禁止目录上跳级别
            if (StringUtils.contains(resource, ".."))
            {
                return false;
            }
    
            // 检查允许下载的文件规则
            if (ArrayUtils.contains(com.dechnic.common.utils.file.MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, com.dechnic.common.utils.file.FileTypeUtils.getFileType(resource)))
            {
                return true;
            }
    
            // 不在允许下载的文件规则
            return false;
        }
    
        /**
         * 下载文件名重新编码
         *
         * @param request 请求对象
         * @param fileName 文件名
         * @return 编码后的文件名
         */
        public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException
        {
            final String agent = request.getHeader("USER-AGENT");
            String filename = fileName;
            if (agent.contains("MSIE"))
            {
                // IE浏览器
                filename = URLEncoder.encode(filename, "utf-8");
                filename = filename.replace("+", " ");
            }
            else if (agent.contains("Firefox"))
            {
                // 火狐浏览器
                filename = new String(fileName.getBytes(), "ISO8859-1");
            }
            else if (agent.contains("Chrome"))
            {
                // google浏览器
                filename = URLEncoder.encode(filename, "utf-8");
            }
            else
            {
                // 其它浏览器
                filename = URLEncoder.encode(filename, "utf-8");
            }
            return filename;
        }
    
        /**
         * 下载文件名重新编码
         *
         * @param response 响应对象
         * @param realFileName 真实文件名
         */
        public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException
        {
            String percentEncodedFileName = percentEncode(realFileName);
    
            StringBuilder contentDispositionValue = new StringBuilder();
            contentDispositionValue.append("attachment; filename=")
                    .append(percentEncodedFileName)
                    .append(";")
                    .append("filename*=")
                    .append("utf-8''")
                    .append(percentEncodedFileName);
    
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
            response.setHeader("Content-disposition", contentDispositionValue.toString());
            response.setHeader("download-filename", percentEncodedFileName);
        }
    
        /**
         * 百分号编码工具方法
         *
         * @param s 需要百分号编码的字符串
         * @return 百分号编码后的字符串
         */
        public static String percentEncode(String s) throws UnsupportedEncodingException
        {
            String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
            return encode.replaceAll("\\+", "%20");
        }
    
        /**
         * 获取图像后缀
         *
         * @param photoByte 图像数据
         * @return 后缀名
         */
        public static String getFileExtendName(byte[] photoByte)
        {
            String strFileExtendName = "jpg";
            if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) && (photoByte[3] == 56)
                    && ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97))
            {
                strFileExtendName = "gif";
            }
            else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70))
            {
                strFileExtendName = "jpg";
            }
            else if ((photoByte[0] == 66) && (photoByte[1] == 77))
            {
                strFileExtendName = "bmp";
            }
            else if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71))
            {
                strFileExtendName = "png";
            }
            return strFileExtendName;
        }
    
        /**
         * 获取文件名称 /profile/upload/2022/04/16/ruoyi.png -- ruoyi.png
         *
         * @param fileName 路径名称
         * @return 没有文件路径的名称
         */
        public static String getName(String fileName)
        {
            if (fileName == null)
            {
                return null;
            }
            int lastUnixPos = fileName.lastIndexOf('/');
            int lastWindowsPos = fileName.lastIndexOf('\\');
            int index = Math.max(lastUnixPos, lastWindowsPos);
            return fileName.substring(index + 1);
        }
    
        /**
         * 获取不带后缀文件名称 /profile/upload/2022/04/16/ruoyi.png -- ruoyi
         *
         * @param fileName 路径名称
         * @return 没有文件路径和后缀的名称
         */
        public static String getNameNotSuffix(String fileName)
        {
            if (fileName == null)
            {
                return null;
            }
            String baseName = FilenameUtils.getBaseName(fileName);
            return baseName;
        }
    
    }
    
    
  • 相关阅读:
    Vue3:响应式数据的基本使用(ref、reactive)
    PIL中的P模式、P模式转为L模式
    UE5_OpenCV库的加载方式
    HBase入门至进阶以及开发等知识梳理
    java计算机毕业设计家庭饮食营养管理源码+mysql数据库+系统+lw文档+部署(2)
    Vue 3 快速上手指南(第二期)
    【无标题】
    【算法】堆排序
    GraalVM安装
    Xcode13 “消失”的Info.plist文件
  • 原文地址:https://blog.csdn.net/u014212540/article/details/127121684