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

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 "文件上传失败";
        }
    }
}
相关推荐
竹之却27 分钟前
如何使用 SakuraFrp 做内网穿透
运维·服务器·网络·frp·内网穿透·sakurafrp
爱学习的小囧33 分钟前
VMware ESXi V7 无 vCenter 虚拟机磁盘缩减攻略:安全释放存储空间(不丢数据)
服务器·网络·windows·安全·esxi·虚拟化
同聘云1 小时前
腾讯云服务器防火墙与网络安全的关系—不可或缺?
服务器·web安全·腾讯云
SPC的存折1 小时前
3、Ansible之playbook模块大全
linux·运维·网络·python
万象.2 小时前
docker镜像操作实操
运维·docker·容器
徐子元竟然被占了!!2 小时前
DNS-特殊域名
运维
源远流长jerry2 小时前
NFV(网络功能虚拟化):重塑未来网络架构的革命性技术
linux·服务器·网络·架构
AlunYegeer2 小时前
【JAVA】网关的管理原理和微服务的Interceptor区分
java·服务器·前端
CDN3602 小时前
CDN 缓存不生效 / 内容不更新?7 种原因 + 一键刷新方案
运维·网络安全·缓存
原来是猿2 小时前
进程间通信(三):命名管道
linux·服务器·网络·git