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

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 "文件上传失败";
        }
    }
}
相关推荐
一起学开源1 小时前
实战总结:BACnet/IP 跨网段通讯的两种解决方案(BBMD 与 Foreign Device)
运维·网络·物联网·bacnet·网络协议·tcp/ip
ALex_zry2 小时前
MySQL运维管理技术手册:从监控到自动化实战
运维·mysql·自动化
凤凰战士芭比Q2 小时前
Linux部署基于Django的博客系统
linux·运维·django
源来猿往2 小时前
高并发之nginx架构
运维·nginx
边疆.3 小时前
【Linux】进程创建、进程终止、进程等待和进程程序替换
linux·运维·服务器·vim·进程控制·进程等待·进程替换
梦想的颜色3 小时前
阿里云ecs云服务器linux安装redis
linux·服务器·阿里云
Y淑滢潇潇4 小时前
RHCE Day5 SELinux
linux·运维·rhce
是垚不是土4 小时前
运维新人踩坑记录:Redis与MySQL生产故障排查&优化手册
运维·数据库·redis·mysql·云计算·bootstrap
snpgroupcn4 小时前
如何在SAP中实现数据验证自动化?5天缩短验证周期,提升转型效率的3大关键策略
运维·人工智能·自动化
optimistic_chen4 小时前
【Linux 系列】Linux 命令/快捷键详解
linux·运维·服务器·ubuntu·命令行·快捷键