vue -element-ui 文件上传upload 组件 实现 及其后台

1、前台

action 不用改 :https://jsonplaceholder.typicode.com/posts/

 <el-upload
              action="https://jsonplaceholder.typicode.com/posts/"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-change="handleChange"
              :file-list="fileList"
              :http-request="getFile"
            >
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt />
              </el-dialog>
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-button size="small" type="success" @click="upload">确认上传</el-button>

getFile: 获取文件

data(){
  return {
   file: {},
   fileList: []
      }
     }
     
//上传方法
 getFile(item) {
      console.log(item.file)
      this.file = item.file
    },
    upload() {
    const fd = new FormData();
      fd.append("filename", this.file);
      const config = { headers: { "Content-Type": "multipart/form-data" } };
      this.$ajax
        .post("/gateway/basedata/center/subject/uploading", fd, config)
        .then(
          response => {
            this.$message.success(response.data.head.message);
            var url = response.data.body.data;
            this.addForm.imageUrl = url;
            this.editForm.imageUrl = url;
            console.log(url);
          },
          function() {
            this.addForm.imageUrl = "";
            console.log("error");
            console.log("total查询失败");
          }
        );
    },

  //弹窗的照片处理
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      console.log("图片预览:");
      this.dialogVisible = true;
      this.dialogImageUrl = file.url;
    },
    handleChange(file, fileList) {
      fileList.splice(0);
      fileList.push(file);
      let formData = new FormData();
      formData.append("file", file);
      console.log(formData.getAll("file"));
      this.addForm.imageUrl = file.url;
      this.editForm.imageUrl = file.url;
      console.log("editForm图片地址:" + this.editForm.imageUrl);
      console.log("addForm图片地址:" + this.addForm.imageUrl);
    },

2、后台

1)控制器代码
  @PostMapping(value = "/uploading")
    public @ResponseBody
    CommonResponse<Integer> uploadFile(@RequestParam("filename") MultipartFile file) throws Exception {
        File file1 = FileUtil.multipartFileToFile(file);
        String url = UploadImage.upImage(file1);

        log.info("图片新地址:" + url);
        String message = "成功上传图片";
        CommonResponse<Integer> commonResponse = buildCommponResponse("1", null, message, 1, url);
        log.info(commonResponse.toString());
        return commonResponse;
    }2)  文件工具类
   package boss.bes.basedata.myutil;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtil {
    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除本地临时文件
     * @param file
     */
    public static void delteTempFile(File file) {
        if (file != null) {
            File del = new File(file.toURI());
            del.delete();
        }
    }

}3)上传至OSS的部分代码
     /**
     * 上传图片至OSS
     * @param file 上传的文件
     * @return String 返回的唯一MD5数字签名
     * */
    public static  String upImage(File file) {
        String resultStr = null;
        try {
            //以输入流的形式上传文件
            InputStream is = new FileInputStream(file);
            //文件名
            String fileName = file.getName();
            String[] files = fileName.split("\\.");
            SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String datetimes = tempDate.format(new Date());
            fileName = files[0]+"-"+datetimes+"."+files[1];
            //文件大小
            Long fileSize = file.length();
            //创建上传Object的Metadata
            ObjectMetadata metadata = new ObjectMetadata();
            //上传的文件的长度
            metadata.setContentLength(is.available());
            //指定该Object被下载时的网页的缓存行为
            metadata.setCacheControl("no-cache");
            //指定该Object下设置Header
            metadata.setHeader("Pragma", "no-cache");
            //指定该Object被下载时的内容编码格式
            metadata.setContentEncoding("utf-8");
            //文件的MIME,定义文件的类型及网页编码,决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成,
            //如果没有扩展名则填默认值application/octet-stream
            metadata.setContentType(getContentType(fileName));
            //指定该Object被下载时的名称(指示MINME用户代理如何显示附加的文件,打开或下载,及文件名称)
            metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
            //上传文件   (上传文件流的形式)
            PutObjectResult putResult = ossClient.putObject(bucketName, folder + fileName, is, metadata);
            //解析结果
            resultStr = putResult.getETag();
            resultStr = getURL("image/"+fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultStr;
    }

3、效果演示
在这里插入图片描述

  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值