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

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 "文件上传失败";
        }
    }
}
相关推荐
The star"'12 小时前
ceph(5-8)
运维·ceph·云计算
The star"'12 小时前
ceph(1-4)
运维·ceph
wanhengidc13 小时前
云手机 网络连接与持续性的表现如何
运维·服务器·科技·游戏·智能手机
小猿成长13 小时前
Ubuntu搭建物联网平台(ThingsBoard)教程
linux·运维·ubuntu
代码不行的搬运工13 小时前
RFC6811:BGP前缀源验证
运维·服务器·bgp网络
tokepson14 小时前
香橙派AI Pro个人云平台 - 从零搭建全记录
linux·服务器·技术·记录
月亮!14 小时前
移动端测试重磅升级:跨平台自动化测试框架深度对比
运维·网络·人工智能·测试工具·容器·自动化·测试用例
凯子坚持 c15 小时前
Docker 容器全生命周期管理与运维命令深度解析
运维·docker·php
java_logo16 小时前
MILVUS Docker 容器化部署指南
运维·人工智能·docker·容器·prometheus·milvus
@YDWLCloud16 小时前
用腾讯云国际版搭建全球加速架构:5 分钟实现多地访问提速
服务器·架构·云计算·github·腾讯云