关于前端如何上传文件/服务器如何接受并保存

1.前端代码

javascript 复制代码
<template>
  <div>
    <input type="file" @change="handleFileChange" />
    <button @click="uploadFile">上传头像</button>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      file: null,
    };
  },
  methods: {
    handleFileChange(event) {
      this.file = event.target.files[0];
    },
    async uploadFile() {
      if (!this.file) {
        alert('请选择一个文件');
        return;
      }

      const formData = new FormData();
      formData.append('file', this.file);

      try {
        const response = await axios.post('/AccountAvatar', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        });

        if (response.data.success) {
          alert('文件上传成功');
          console.log('上传成功', response.data);
        } else {
          alert('文件上传失败: ' + response.data.message);
        }
      } catch (error) {
        console.error('上传失败', error);
        alert('上传失败: ' + error.message);
      }
    },
  },
};
</script>

2.后端代码

java 复制代码
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
public class FileUploadController {

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "文件为空";
        }

        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();

            // 将文件保存到服务器上的某个目录
            File dest = new File("/path/to/save/" + fileName);
            file.transferTo(dest);

            return "文件上传成功";
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败";
        }
    }
}
相关推荐
EricFRQ18 分钟前
devops自动化容器化部署
运维·自动化·devops
白云~️1 小时前
uniappx 打包配置32位64位x86安装包
运维·服务器·github
在河之洲木水1 小时前
现代多核调度器的本质 调度三重奏
linux·服务器·系统架构
文牧之2 小时前
PostgreSQL的扩展 pgcrypto
运维·数据库·postgresql
白总Server2 小时前
多智能体系统的中间件架构
linux·运维·服务器·中间件·ribbon·架构·github
2401_867021904 小时前
文件缓冲区(IO与文件 ·III)(linux/C)
linux·运维·服务器·c语言
刘某的Cloud4 小时前
rabbitmq常用命令
linux·运维·分布式·rabbitmq·系统
悄悄敲敲敲5 小时前
Linux:进程间通信->命名管道
linux·运维·服务器
望获linux5 小时前
智能清洁机器人中的实时操作系统应用研究
大数据·linux·服务器·人工智能·机器人·操作系统
io无心5 小时前
Docker绑定端口报错
运维·docker·容器