使用vue+Element的Upload+formData實現圖片傳到SpringBoot,再上傳到fastdfs


前端部分: 

<template>
    <div>
        <el-row>
            <el-col :span="12" :offset="6">
                <div id="demo">
                    <el-row>
                        <el-col :span="24">
                            <div>
                                <el-upload
                                  action=""
                                  list-type="picture-card"
                                  :auto-upload="false"
                                  :limit="5"
                                  :on-preview="handlePictureCardPreview"
                                  :on-remove="handleRemove"
                                  :on-change="fileChange"
                                  :multiple="true"
                                  :file-list="fileList">
                                  <i class="el-icon-plus"></i>
                                </el-upload>

                                <el-dialog :visible.sync="dialogVisible">
                                  <img width="100%" :src="dialogImageUrl" alt="">
                                </el-dialog>
                                
                            </div>
                        </el-col>
                    </el-row>   
                    <el-row>
                        <el-col :span="3" :offset="15">
                            <el-button type="primary" class="btn_pos" @click="uploadImage">上傳</el-button>
                        </el-col>
                    </el-row>
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script>
    import axios from 'axios'
    export default {
        data () {
            return {
                dialogImageUrl: '',
                dialogVisible: false,
          //用來接收緩存中的圖片
                fileList: []
            };
        },

        methods: {
            handleRemove(file, fileList) {
                this.fileList = fileList;
            },
            fileChange(file, fileList){
                this.fileList = fileList;
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },

            uploadImage(){
                let formData = new FormData();
                for(let i = 0; i < this.fileList.length; i++){
                    //this.fileList[i].raw:獲取圖片格式
                    //這里的file必須和后端Controller中的requestparam參數一致,才能上傳成功,否則會報400錯誤
                    formData.append("file", this.fileList[i].raw, this.fileList[i].name);
                }
          //這里重新創建了一個axios實例,是因為我在全局配置里的Content-type是appliacation/json,而這里我想要使用multipart/form-data
                const http1 = axios.create({
                    headers: {
                        // 'Content-Type': 'multipart/form-data'
                        "Content-Type": "multipart/form-data"
                    }
                })
                http1({
                    url: 'http://localhost:8081/lunbo/upload',
                    method: 'post',
                    data: formData
            
                })
                    .then((res) => {
                        console.log(res.data);
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            }
            
        }
    }
</script>
<style scoped>
    .btn_pos{
        margin-top: 0px;
    }
</style>
View Code

后端部分:

pom文件:  

        <dependency>
            <groupId>com.github.tobato</groupId>
            <artifactId>fastdfs-client</artifactId>
            <version>1.27.2</version>
        </dependency>

controller部分:   

@RestController
@RequestMapping("/lunbo")
public class LunboController {

    @Autowired
    private UploadUtill uploadUtill;

    /**
     * 圖片(文件上傳),並返回圖片地址
     */
    @RequestMapping("/upload")
    @ResponseBody //返回界面一個map<"path","....">
    public Map<String,Object> uploadImage(@RequestParam("file") MultipartFile file){

        //判斷文件是否為空(防止出現空指針異常)
        if(file.isEmpty()){
            System.out.println("文件不存在");
        }else{
            System.out.println(file.getOriginalFilename());
        }
        //創建一個HashMap對象
        Map<String, Object> upload =new HashMap<>();
        //返回的fastdfs的路徑
        String path = uploadUtill.uploadImage(file);
        upload.put("path",path);
        return upload;
    }
}
View Code

配置文件部分:

# FastDFS
fdfs:
  so-timeout: 1501
  connect-timeout: 601
  thumb-image: # 縮略圖
    width: 60
    height: 60
  tracker-list: ip:22122

upload:
  base-url: http://ip:8888/
  allow-types:
    - image/jpeg
    - image/jpg
    - image/png
    - image/bmp
    - image/gif

配置類部分:

//@Component
@ConfigurationProperties(prefix = "upload")
public class UploadProperties {

//    @Value("${baseUrlt}")
    private String baseUrl;
    private List<String> allowTypes;

    public String getBaseUrl() {
        return baseUrl;
    }

    public void setBaseUrl(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public List<String> getAllowTypes() {
        return allowTypes;
    }

    public void setAllowTypes(List<String> allowTypes) {
        this.allowTypes = allowTypes;
    }

工具類部分:(因為要經常使用所以把它抽取出來做工具類)

  思路:圖片上傳到fastdfs,然后獲取路徑,在拼接基本的路徑(在application.yml中配置的)   

@Component
@EnableConfigurationProperties(UploadProperties.class)
public class UploadUtill {

//    Log log= LogFactory.getLog(UploadUtill.class);
    Log log= LogFactory.getLog(UploadProperties.class);

    @Autowired
    FastFileStorageClient storageClient;

    @Autowired
    UploadProperties prop;

    @Autowired
    LunboDao lunboDao;

    public String uploadImage(MultipartFile file) {

        // 1、校驗文件類型
        String contentType = file.getContentType();
        if (!prop.getAllowTypes().contains(contentType)) {
            throw new RuntimeException("文件類型不支持");
        }

        // 2、校驗文件內容
        try {
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null || image.getWidth() == 0 || image.getHeight() == 0) {
                throw new RuntimeException("上傳文件有問題");
            }
        } catch (IOException e) {
            log.error("校驗文件內容失敗....{}", e);
            throw new RuntimeException("校驗文件內容失敗"+e.getMessage());
        }
        try {

            // 3、上傳到FastDFS
            // 3.1、獲取擴展名
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            // 3.2、上傳
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);

            // 返回路徑
            String path = prop.getBaseUrl() + storePath.getFullPath();
            //存入數據庫
            LunboEntity lunboEntity = new LunboEntity();
            lunboEntity.setImgUrl(path);
            lunboEntity.setId(3);
            lunboDao.insert(lunboEntity);
            return path;


        } catch (IOException e) {
            log.error("【文件上傳】上傳文件失敗!....{}", e);
            throw  new RuntimeException("【文件上傳】上傳文件失敗!"+e.getMessage());
        }
    }
}
View Code

 注意:

  如果業務中不需要點擊按鈕,這時候可以使用  :http-request="uploadImage" 來直接觸發該方法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM