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

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 "文件上传失败";
        }
    }
}
相关推荐
Flash.kkl4 小时前
Linux——进程信号
运维·服务器
苏宸啊5 小时前
Linux权限
linux·运维·服务器
Gofarlic_oms16 小时前
Windchill用户登录与模块访问失败问题排查与许可证诊断
大数据·运维·网络·数据库·人工智能
我是小疯子666 小时前
Python变量赋值陷阱:浅拷贝VS深拷贝
java·服务器·数据库
xqhoj6 小时前
Linux——make、makefile
linux·运维·服务器
文亭湖畔程序猿6 小时前
Debian 12 日常命令 & nano 快捷键速查表
运维·debian
张童瑶6 小时前
Linux 在线安装编译Python3.11
linux·运维·python3.11
ziqibit6 小时前
debian Live with Persistence 持久化U盘的debian系统
运维·debian
Shi_haoliu6 小时前
SolidTime 在 Rocky Linux 9.5 上的完整部署流程
linux·运维·nginx·postgresql·vue·php·laravel
lifejump6 小时前
Pikachu | XXE
服务器·web安全·网络安全·安全性测试