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

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 "文件上传失败";
        }
    }
}
相关推荐
独行soc1 小时前
2025年渗透测试面试题总结-字某跳动-安全研究实习生(三面)(题目+回答)
linux·服务器·安全·web安全·面试·职场和发展
爱吃烤鸡翅的酸菜鱼2 小时前
Java【网络原理】(3)网络编程续
java·运维·服务器·网络
daizikui2 小时前
LVS+Nginx接入层架构图
服务器·nginx·lvs
饭九钦vlog7 小时前
机器人匹诺曹机制,真话假话平衡机制
服务器·经验分享·新浪微博
kyle~8 小时前
linux根目录
linux·服务器
QuiteCoder8 小时前
【Linux】软硬连接与动静态库
linux·运维·服务器
꧁༺朝花夕逝༻꧂8 小时前
Linux基础--用户管理
linux·运维
Narutolxy9 小时前
Ubuntu 下 Docker 企业级运维指南:核心命令与最佳实践深度解析20250309
运维·ubuntu·docker
鹿屿二向箔9 小时前
72MHz的MCU能支持多大频率的传感器数据采样率?
服务器·网络·单片机
明明跟你说过9 小时前
在【k8s】中部署Jenkins的实践指南
运维·ci/cd·云原生·容器·kubernetes·jenkins