springboot + vue + FastDFS实现文件上传(支持预览)

准备FastDFS环境点击

准备springboot环境

pom.xml


            <dependency>
                <groupId>net.oschina.zcx7878</groupId>
                <artifactId>fastdfs-client-java</artifactId>
                <version>1.27.0.0</version>
            </dependency>

新增配置文件fastdfs-client.properties

fastdfs.connect_timeout_in_seconds = 5
fastdfs.network_timeout_in_seconds = 30
fastdfs.charset = UTF-8
fastdfs.http_anti_steal_token = false
fastdfs.http_secret_key = FastDFS1234567890
fastdfs.http_tracker_http_port = 80

fastdfs.tracker_servers = 你的虚拟机端口ip:22122

fastdfs.connection_pool.enabled = true
fastdfs.connection_pool.max_count_per_entry = 500
fastdfs.connection_pool.max_idle_time = 3600
fastdfs.connection_pool.max_wait_time_in_ms = 1000

创建一个until类 FastUtils

package com.vue.until;

import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 *
 * 文件上传工具类
 */
public class FastUtils {

    private static StorageClient1 client1 ;
    static {
        try {
            ClientGlobal.initByProperties("fastdfs-client.properties");
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getConnection();
            client1 = new StorageClient1(trackerServer, null);
        }catch (IOException e){
            e.printStackTrace();
        }
        catch (MyException e){
            e.printStackTrace();
        }

    }



    public static String upload(MultipartFile file){
        String oldName = file.getOriginalFilename();

        try {
            return client1.upload_file1(file.getBytes(),oldName.substring(oldName.lastIndexOf(".") + 1),null);

        }
        catch (IOException e){
            e.printStackTrace();
        }
        catch (MyException e){
            e.printStackTrace();
        }

        return null;
    }

}

基于MVC设计模型,新增一个service服务层

package com.vue.serivce;


import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class UploadService {

    public String upload(MultipartFile file) {
      return null;
    }
}

controller层 UploadController

package com.vue.contorller;


import com.vue.serivce.UploadService;
import com.vue.until.FastUtils;
import com.vue.until.ResultEntity;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.swing.plaf.metal.MetalIconFactory;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("/upload")
@CrossOrigin
public class UploadController {
    @Autowired
    private UploadService uploadService;


    @PostMapping("/import")
    public String importData(MultipartFile file, HttpServletRequest req) throws IOException {

        System.out.println("file = " + file);
        String realPath = req.getSession().getServletContext().getRealPath("/");
//        file.transferTo(new File(realPath));

        System.out.println("realPath = " + realPath);
        String fileId = FastUtils.upload(file);
        String url = "http://192.168.56.10/" + fileId;
        System.out.println(url);
        return url;
    }
}

测试上传:

   // 文件上传
    @Test
    void testUpload() {
        try {
            ClientGlobal.initByProperties("fastdfs-client.properties");
            TrackerClient tracker = new TrackerClient();
            TrackerServer trackerServer = tracker.getConnection();
            StorageServer storageServer = null;
            StorageClient1 client = new StorageClient1(trackerServer, storageServer);
            NameValuePair nvp[] = null;
            //上传到文件系统
            String fileId = client.upload_file1("C:\\Users\\think\\Documents\\1.pdf", "pdf",
                    nvp);
//            logger.info(fileId);
            System.err.println(fileId);
//            Logger.g
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


运行结果
在这里插入图片描述
在这里插入图片描述
测试文件下载功能

 @Test
    void testDownload() {
        try {
            ClientGlobal.initByProperties("fastdfs-client.properties");
            TrackerClient tracker = new TrackerClient();
            TrackerServer trackerServer = tracker.getConnection();
            StorageServer storageServer = null;
            StorageClient1 client = new StorageClient1(trackerServer, storageServer);
            byte[] bytes = client.download_file1("group1/M00/00/00/wKg4CmEHlfKAJyKsAAY5stCGm7U909.pdf");
            FileOutputStream fos = new FileOutputStream(new File("C:\\Users\\think\\Desktop\\a.pdf"));
            fos.write(bytes);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

在这里插入图片描述
在这里插入图片描述

Vue环境准备

Vue cli3.0 + Element ui(upload组件)

Upload.Vue

<template>
  <div>
    <el-upload
      style="display: inline"
      :show-file-list="true"
      :on-success="onSuccess"
      :on-error="onError"
      :before-upload="beforeUpload"
      @click="isAcitve"
      action="http://localhost:8080/upload"
    >
      <el-button
        size="mini"
        type="success"
        @click="isAcitve"
        :icon="uploadBtnIcon"
      >上传简历
     </el-button>
    </el-upload>
    <a @click="open_page">预览页面</a>
    <div class="demo-fit">
      
      <div class="block" v-for="fit in fits" :key="fit">
        <span class="title">{{ fit }}</span>
        <el-avatar shape="square" :size="100" :fit="fit" :src="url"></el-avatar>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      enabledUploadBtn: true,
      uploadBtnIcon: 'el-icon-upload2',
      url: '',
      fits: ['fill', 'contain', 'cover', 'none', 'scale-down'],
     
    };
  },
  methods: {
    onSuccess(response, file, fileList) {
      // window.location.href=response
        console.log(file)
        console.log(fileList)
      alert(response);
      this.url = response;

      this.enabledUploadBtn = true;
      this.uploadBtnIcon = 'el-icon-upload2';
      this.btnText = '数据导入';
    },
    onError(err, file, fileList) {
      this.enabledUploadBtn = true;
      this.uploadBtnIcon = 'el-icon-upload2';
      this.btnText = '数据导入';
    },
    beforeUpload(file) {
      this.enabledUploadBtn = false;
      this.uploadBtnIcon = 'el-icon-loading';
      this.btnText = '正在导入';
    },
    open_page(){
        window.open(this.url)
    },
    isAcitve(){
        alert(1)
        return false
    }
  }
};
</script>

<style>
</style>

测试上传
在这里插入图片描述

在这里插入图片描述

点击预览

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

唐 昊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值