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

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 "文件上传失败";
        }
    }
}
相关推荐
橘子真甜~16 分钟前
C/C++ Linux网络编程13 - 传输层TCP协议详解(面向字节流和有连接)
linux·运维·服务器·c语言·网络·c++·tcp/ip
嘻哈baby18 分钟前
systemd服务管理深入实践从入门到自定义服务
linux·服务器·网络
qq_54702617924 分钟前
Docker 搭建Nexus3私服
运维·docker·容器
June`35 分钟前
SSH连接原理与守护进程实战
linux·运维·服务器
JH灰色1 小时前
【大模型】-LangChain--stream流式同步异步
服务器·前端·langchain
CQ_YM1 小时前
Linux进程基础
linux·服务器·进程
driver19991 小时前
hyperV装的windows11安装docker不支持虚拟化
运维·docker·容器
_OP_CHEN2 小时前
【Git原理与使用】(五)Git 多人协作:从分支协作到冲突解决,团队开发效率翻倍秘籍
linux·运维·git·团队开发·运维开发·企业级组件·git多人协作