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

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 "文件上传失败";
        }
    }
}
相关推荐
new_daimond7 分钟前
Linux 服务器内存监控与优化指南
linux·服务器·chrome
一介草民丶12 分钟前
Linux | Mongodb 6 离线安装
linux·运维·mongodb
mc23561 小时前
Linux实用操作
linux·运维·服务器
半梦半醒*2 小时前
k8s——pod详解2
linux·运维·docker·容器·kubernetes·负载均衡
vvw&2 小时前
如何使用 Nodemon 自动重启 Node.js 应用
linux·运维·服务器·node.js
GIS数据转换器2 小时前
2025无人机在电力交通中的应用实践
运维·人工智能·物联网·安全·无人机·1024程序员节
Elendill2 小时前
【Ubuntu】Ubuntu 服务器升级系统操作记录
运维·服务器·ubuntu
北亚数据恢复3 小时前
服务器数据恢复—Raid5阵列热备盘同步失败,数据恢复揭秘
运维·服务器
利刃大大3 小时前
【高并发服务器:HTTP应用】十五、HttpRequest请求模块 && HttpResponse响应模块设计
服务器·c++·http·项目
Matana1113 小时前
Vmware中主机ip a没有ip地址
服务器·网络·tcp/ip