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

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 "文件上传失败";
        }
    }
}
相关推荐
疯狂吧小飞牛3 小时前
GPG基础指令
linux·服务器·网络
C++ 老炮儿的技术栈3 小时前
volatile使用场景
linux·服务器·c语言·开发语言·c++
hjxu20164 小时前
【OpenClaw 龙虾养成笔记一】在远程服务器,使用Docker安装OpenClaw
服务器·笔记·docker
todoitbo5 小时前
用虚拟局域网打通 Win/Mac/Linux 三端:跨设备协作的实用方案
linux·运维·macos
Sylvia-girl6 小时前
Linux下的基本指令1
linux·运维·服务器
CDN3606 小时前
360CDN SDK 游戏盾:轻量化接入 + 强防护实测
运维·游戏·网络安全
Stewie121386 小时前
Docker 面试题
运维·docker·容器
斯班奇的好朋友阿法法7 小时前
在企业的离线内网环境的服务器部署openclaw和大模型
服务器·语言模型
星纬智联技术7 小时前
GEO E2E 自动化验证测试文章
运维·自动化·geo
天赐学c语言7 小时前
Linux - 应用层自定义协议与序列/反序列化
linux·服务器·网络·c++