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

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 "文件上传失败";
        }
    }
}
相关推荐
gwjcloud14 分钟前
Frp内网穿透
linux·运维·服务器
MwEUwQ3Gx23 分钟前
常见Linux权限提升笔记
linux·运维·笔记
bIo7lyA8v25 分钟前
如何用SSH访问远程服务器上的内网服务(如:MySQL、Redis、Kafka)?
服务器·mysql·ssh
小邓睡不饱耶40 分钟前
花店花品信息管理系统开发实战:Python实现简易门店管理系统
服务器·python·microsoft
ken22321 小时前
安装问题@ ubuntu 24.04 :efi 磁盘分区,挂载
linux·运维·ubuntu
white-persist1 小时前
【vulhub weblogic CVE-2017-10271漏洞复现】vulhub weblogic CVE-2017-10271漏洞复现详细解析
java·运维·服务器·网络·数据库·算法·安全
TON_G-T2 小时前
useEffect为什么会触发死循环
java·服务器·前端
tHeya06II2 小时前
涵盖 Cursor、Claude Code、Skills
java·服务器
maosheng11462 小时前
Linux的第二次作业
linux·运维·服务器
maosheng11462 小时前
Linux
linux·运维·服务器