SpringBoot+Vue+ElementUI实现图片和表单一起上传
    		       		warning:
    		            这篇文章距离上次修改已过429天,其中的内容可能已经有所变动。
    		        
        		                
                在Spring Boot中,你可以使用MultipartFile接收前端传送的文件,并处理文件的保存。在Vue中,你可以使用ElementUI的<el-upload>组件来实现文件的上传。
以下是一个简单的例子:
后端(Spring Boot):
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
 
@RestController
public class FileUploadController {
 
    private static final String UPLOAD_DIR = "uploads/";
 
    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file, @RequestParam("data") String formData) {
        if (file.isEmpty()) {
            return "File upload failed.";
        }
 
        try {
            // 保存文件
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOAD_DIR + file.getOriginalFilename());
            Files.write(path, bytes);
 
            // 处理表单数据
            // ...
 
            return "File upload success.";
        } catch (IOException e) {
            e.printStackTrace();
            return "File upload failed.";
        }
    }
}前端(Vue):
<template>
  <div>
    <el-form ref="form" :model="form" label-width="80px">
      <!-- 其他表单字段 -->
      <el-form-item label="文件">
        <el-upload
          action="http://localhost:8080/upload"
          :on-success="handleSuccess"
          :on-error="handleError"
          name="file">
          <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      form: {
        // 表单数据
      }
    };
  },
  methods: {
    handleSuccess(response, file, fileList) {
      console.log('File uploaded successfully:', response);
    },
    handleError(err, file, fileList) {
      console.error('Error during upload:', err);
    },
    submitForm() {
      const formData = new FormData();
      formData.append('data', JSON.stringify(this.form));
      // 获取el-upl
评论已关闭