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

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 "文件上传失败";
        }
    }
}
相关推荐
熙客11 分钟前
Linux:监控命令
linux·运维
飞鱼&12 分钟前
Linux 常用命令
linux·运维·服务器
喵了几个咪24 分钟前
使用Bazel构建你的Kratos微服务
java·运维·微服务
努力还债的学术吗喽36 分钟前
ffmpeg离线安装到服务器:解决conda/sudo/无法安装的通用方案
服务器·ffmpeg·conda
偶像你挑的噻1 小时前
4-Linux驱动开发-字符设备驱动
linux·运维·驱动开发
2401_865854881 小时前
AI软件可以帮助我自动化哪些日常任务?
运维·人工智能·自动化
qq_401700411 小时前
Linux 信号机制
linux·运维·服务器
_Stellar1 小时前
Linux 服务器配置 rootless docker Quick Start
linux·服务器·docker
石像鬼₧魂石2 小时前
Kali Linux 中对某(靶机)监控设备进行漏洞验证的完整流程(卧室监控学习)
linux·运维·学习
Hqst_xiangxuajun2 小时前
服务器主板选用网络变压器及参数配置HX82409S
运维·服务器·网络