如何前端上傳檔案

xb_bbai發表於2020-10-14

 

1.前端formdata 傳參

2.後端 通過

 

前端:

 <el-upload ref="upload" action="" class="upload-demo" :on-preview="handlePreview"
  :on-remove="handleRemove" :before-upload="uploadImage" :file-list="fileList"
  :on-change="filechange" style="display:inline-block">
     <el-button slot="trigger" size="mini" type="primary" icon="el-icon-upload">匯入</el-button>
  </el-upload>
<script>
  for (var foda of this.fileList) {
     formData.append("file", foda.raw);
   }
                        var filename = this.fileList[0].name;
                    var that = this;
                    //1.匯入wps 檔案
                    $.ajax({
                        url: globedataserverurl + "/FileUploadData/FileUploadData.do",
                        type: 'POST',
                        async: false,
                        dataType: 'json',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function (data) {
                            if (data == true) {
                                that.$message({
                                    type: 'success',
                                    message: '匯入成功11111!'
                                });

                            }
                        },
                        error(err) {
                            console.log(err);
                            that.$message.error('未獲取到資料');
                        }
                    });
</script>

依賴

 <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.4</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

 

後端:

 

package com.ev.projectserver.utils;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class FileUpLoad {
    /**
     * form表單上傳 通用檔案上傳介面
     * @param request
     * @param savePath 儲存路徑
     * @return
     */
    public  static  boolean formFileUpLoad(HttpServletRequest request, String savePath){
        boolean isscloadfile=false;
        //將上下文初始化給 CommonsMutipartResolver (多部分解析器)
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getServletContext());
        //檢查form 是否有encype=" mutipart/form-data"
        if(multipartResolver.isMultipart(request)){
            //將request 變成多部分request
            MultipartHttpServletRequest params=((MultipartHttpServletRequest) request);

            List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                    .getFiles("file");
            //獲取檔名稱
            String s=params.getParameter("path");
            BufferedOutputStream stream = null;
            if(s!=null&&s!="") savePath=savePath+"/"+s;
            String sPath=savePath;//獲取檔名路徑

            //判斷檔案是否
            File file = new File(sPath);
            //判斷上傳檔案的儲存目錄是否存在
            if (!file.exists() && !file.isDirectory()) {
//                System.out.println(sPath+"目錄不存在,需要建立");
                //建立目錄
                file.mkdirs();
            }
            for(MultipartFile multipartFile :files){
                String fileName=multipartFile.getOriginalFilename();
                int size= (int) multipartFile.getSize();
                System.out.println(fileName+" "+size);
                if(fileName.isEmpty()){
                    break;
                }
                File dest=new File(sPath+"/"+fileName);
                //判斷檔案的父目錄是否存在,不存在則建立
                if(!dest.getParentFile().exists()){
                    dest.getParentFile().mkdir();
                }
                try {
                    multipartFile.transferTo(dest);
                    isscloadfile=true;
                } catch (IOException e) {
                    isscloadfile=false;
                    e.printStackTrace();
                }


            }
        }
        return  isscloadfile;
    }

    /**
     * 遍歷某個資料夾下的所有的檔案
     * @param dname 需要遍歷資料夾名稱
     * @return 檔名稱列表
     */
    public static List<String> getOneDirectoryFiles(String dname){
        List<String> fileList=new ArrayList<>();
        File file=new File(dname);
        if(file.exists() && file.isDirectory()){
            File[]  files= file.listFiles();
           for(File fs:files){
                fileList.add(fs.getName());
           }
        }
        return fileList;
    }

    /**
     * 遍歷某個資料夾,所有的檔案
     * @param file
     * @return
     */
    public static void getDirectoryFiles(File file,List<String> fileList){
        if(file.exists() &&file.isDirectory()){
            File[] files= file.listFiles();
            for(File fs:files){
                if(fs.isDirectory()){
                    getDirectoryFiles(fs,fileList);
                }else {
                    fileList.add(fs.getName());
                }
            }
        }
    }

}

 

 

相關文章