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

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 "文件上传失败";
        }
    }
}
相关推荐
人工智能训练5 小时前
OpenEnler等Linux系统中安装git工具的方法
linux·运维·服务器·git·vscode·python·ubuntu
郭涤生6 小时前
第十章_信号_《UNIX环境高级编程(第三版)》_笔记
服务器·笔记·unix
QT 小鲜肉6 小时前
【Linux命令大全】001.文件管理之which命令(实操篇)
linux·运维·服务器·前端·chrome·笔记
额呃呃7 小时前
select详细分析
服务器
网创联盟,知识导航7 小时前
沐雨云香港大宽带云服务器 · 配置全览
服务器·阿里云·腾讯云
fantasy5_58 小时前
Linux 动态进度条实战:从零掌握开发工具与核心原理
linux·运维·服务器
weixin_462446238 小时前
exo + tinygrad:Linux 节点设备能力自动探测(NVIDIA / AMD / CPU 安全兜底)
linux·运维·python·安全
不瘦80斤不改名8 小时前
Python 日志(logging)全解析
服务器·python·php
莫逸风8 小时前
【局域网服务方案】:无需找运营商,低成本拥有高性能服务器
运维·服务器
oMcLin8 小时前
CentOS 7 频繁出现 “Connection Refused” 错误的原因分析与解决
linux·运维·centos