SpringBoot+Vue3 realizes uploading files

foreword

When developing the background system, I often encounter the function of uploading files. Here is my method.


Backend: SpringBoot2
Frontend: Vue3+ElementPlus
Tool: IDEA


1. Backend

/**
     * 上传采购合同PDF
     *
     * @author Leo高洋
     * @create 2023-01-20 6:51
     */
    @PostMapping("/uploadContract")
    public Map<String, Object> uploadContract(MultipartFile file) throws Exception {
    
    
        Map<String, Object> resultMap = new HashMap<>();
        if (!file.isEmpty()) {
    
    
            logger.info("上传采购合同PDF");
            String originalFilename = file.getOriginalFilename();// 获取文件名称
            String fileName = originalFilename.substring(0, originalFilename.indexOf("."));// 获取前缀
            String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));// 获取后缀
            String newFileName = fileName + "-" + DateUtil.getCurrentDatePath() + suffixName;// 根据上传时间重新命名合同
            // 根据定义的位置存入合同
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(contractPdfFilePath + newFileName));
            resultMap.put("code", 0);
            resultMap.put("msg", "上传成功");
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("title", newFileName);
            resultMap.put("data", dataMap);
        }
        return resultMap;
    }

The MultipartFile tool class for uploading files using SpringMVC is used here. The specific interface methods of the tool class are only demonstrated here for simple use. If you are interested, you can check the article MultipartFile tool class (method detailed explanation) .
When defining a method, parameters need to be passed in, and the parameter type is MultipartFile. Here I add the operation of judging whether the file is empty, which can be modified by yourself.

  1. file.getOriginalFilename(); Get the name of the file
  2. originalFilename.substring(0, originalFilename.indexOf(“.”)); intercept prefix
  3. originalFilename.substring(originalFilename.lastIndexOf(“.”)); Get the suffix and file type
  4. fileName + "-" + DateUtil.getCurrentDatePath() + suffixName; Rename the file according to the upload time
  5. FileUtils.copyInputStreamToFile(file.getInputStream(), new File(contractPdfFilePath+ newFileName)); Deposit the contract according to the defined location

The contractPdfFilePath here is a pre-defined location. I configure it globally in the application.yml file, and then introduce it in the controller, as follows:

application.yml:

contractPdfFilePath: E://2023GraduationDesign/uploadFile/AssetPurchaseContract/

Controller:

@Value("${contractPdfFilePath}")
private String contractPdfFilePath;

It can be used directly after configuration, or can be defined directly in the controller! In order to facilitate whether the upload was successful some time ago, the file name is passed into the Map collection and returned to the front end, namely:

Map<String, Object> dataMap = new HashMap<>();
dataMap.put("title", newFileName);

The general process is as above, and the back end is completed!

Note : There is a defect in uploading files here, which is to upload the specified location immediately after selecting the file. If you find that the file is wrongly uploaded in the actual application, the file is already in the specified folder when you re-select, and there is no overwriting. Personally, I feel harmless, but in The new filename is overwritten when the frontend echoes the filename.

Supplement : The above code has the DateUtil.getCurrentDatePath() method when splicing the new file name. It is the date tool class I encapsulated to get the current time. If you are interested, you can study it yourself. I won’t go into details here, and the code is pasted below. Or renaming can be designed according to your own preferences, or you don't need to rename.

package com.project.util;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 日期工具类
 */
public class DateUtil {
    
    

	/**
	 * 日期对象转字符串
	 * @param date
	 * @param format
	 * @return
	 */
	public static String formatDate(Date date,String format){
    
    
		String result="";
		SimpleDateFormat sdf=new SimpleDateFormat(format);
		if(date!=null){
    
    
			result=sdf.format(date);
		}
		return result;
	}
	
	/**
	 * 字符串转日期对象
	 * @param str
	 * @param format
	 * @return
	 * @throws Exception
	 */
	public static Date formatString(String str,String format) throws Exception{
    
    
		if(StringUtil.isEmpty(str)){
    
    
			return null;
		}
		SimpleDateFormat sdf=new SimpleDateFormat(format);
		return sdf.parse(str);
	}
	
	public static String getCurrentDateStr(){
    
    
		Date date=new Date();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddhhmmssSSSSSSSSS");
		return sdf.format(date);
	}
	
	public static String getCurrentDatePath()throws Exception{
    
    
		Date date=new Date();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
		return sdf.format(date);
	}
	
	public static void main(String[] args) {
    
    
		try {
    
    
			System.out.println(getCurrentDateStr());
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
	}
}

Two, the front end

insert image description here

<!-- 上传合同 -->
        <el-form-item label="上传合同" prop="cght">
          <el-upload
                  class="upload-demo"
                  :herders="headers"
                  :action="getServerUrl()+'asset/uploadContract'"
                  :limit="1"
                  :show-file-list="false"
                  :on-success="handleContractSuccess"
          >
            <el-row>
              <el-button type="primary">添加采购合同</el-button>
              <span style="font-size: 13px;color: #8d8d8d;margin-left: 15px">{
   
   { fileName }}</span>
            </el-row>
          </el-upload>
        </el-form-item>

Here: getServerUrl() in action is the axios method encapsulated by itself, which means http://localhost:8082/. You can write directly.

  1. Splicing url: getServerUrl()+'asset/uploadContract'
  2. handleContractSuccess: method for custom upload success

handleContractSuccess method:

const fileName = ref("只允许上传PDF文件")
const handleContractSuccess = (res) => {
    
    
  fileName.value = res.data.title;
  form.value.cght = res.data.title;
}

When the upload is successful, " Only allow uploading of PDF files " on the right side is replaced with the file name, and the file name is passed into the defined attribute to upload to the database.

3. Demonstration

insert image description here
insert image description here
insert image description here

You can see that the file is uploaded successfully, uploaded to the specified location and renamed successfully displayed on the form

The process is as above, and the front end is completed!


Finish

The above is all the content, welcome to discuss, record learning!

Guess you like

Origin blog.csdn.net/m0_59420288/article/details/128768843
Recommended