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

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 "文件上传失败";
        }
    }
}
相关推荐
AC赳赳老秦7 分钟前
招投标公开数据自动化采集实战:基于 OpenClaw 的定时抓取与业务关键词精准推送
运维·服务器·数据库·自动化·测试用例·deepseek·openclaw
小的博客11 分钟前
windows下安装Docker Desptop
运维·docker·容器
酷可达拉斯14 分钟前
Linux操作系统-shell编程(0)
linux·运维·服务器·python·云计算
2301_7779983431 分钟前
Linux中断机制:操作系统如何高效运行
linux·运维·服务器
emfuture1 小时前
工业自动化现场四大典型故障复盘:从环境适配到边缘智能的工程实践
运维·网络·自动化
星栈独行1 小时前
Node 接口该写同步还是异步?
服务器·开发语言·后端·程序人生·node.js
笑锝没心没肺1 小时前
yum update 报错:GPG key retrieval failed: [Errno 14] HTTPS Error 404 - Not Found
linux·运维·服务器
keke.shengfengpolang1 小时前
自动化专业毕业能干什么?制造业、控制、软件、数据怎么选,2026版大实话
运维·自动化
汤永红1 小时前
gtk-x11-2.0.so.0
linux·运维·服务器
公众号:fuwuqiBMC2 小时前
(转自“服务器BMC”)服务器BMC芯片功能——网口
运维·服务器