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

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 "文件上传失败";
        }
    }
}
相关推荐
mobai725 分钟前
Ubuntu环境上安装NTP服务
linux·运维·ubuntu
郝学胜-神的一滴27 分钟前
Linux Socket编程核心:深入解析sockaddr数据结构族
linux·服务器·c语言·网络·数据结构·c++·架构
loong_XL5 小时前
docker gpu容器镜像环境构建
运维·docker·容器
杨了个杨89826 小时前
nginx常见功能部署
运维·服务器·nginx
小天源8 小时前
linux漏洞一键扫描
linux·运维·服务器·漏洞扫描
eWidget8 小时前
InfluxDB迁移至金仓数据库的同城容灾实践:性能显著提升、运维效率优化,某能源企业实现RPO_5秒的高可靠时序数据管理
运维·数据库·能源·时序数据库·kingbase·kingbasees·金仓数据库
m0_696212688 小时前
个人微信api
运维·服务器
en-route9 小时前
SSH Key 与 GPG Key 区别详解:Git 使用中的身份与签名机制
运维·git·ssh
Web极客码9 小时前
区块链第 1 层与第 2 层有什么区别?
服务器·区块链
小白鸽i11 小时前
【LINUX】将源码驱动文件编译并生效
linux·运维·服务器