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

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 "文件上传失败";
        }
    }
}
相关推荐
子正6 分钟前
一键编译包含多个独立模块和应用的工程(linux cmake)
linux·运维·cmake
小阳睡不醒7 分钟前
小白成长之路-Linux Shell脚本练习
linux·运维·服务器
dessler37 分钟前
代理服务器-LVS的DR模式
linux·运维·云计算
知之则吱吱2 小时前
亚马逊AWS云服务器高效使用指南:最大限度降低成本的实战策略
服务器·云计算·aws
cui_win2 小时前
每日一令:Linux 极简通关指南 - 汇总
linux·运维·服务器
知星小度S2 小时前
Linux权限探秘:驾驭权限模型,筑牢系统安全
linux·运维·服务器
Kaede65 小时前
如何应对Linux云服务器磁盘空间不足的情况
linux·运维·服务器
Zfox_7 小时前
Redis:Hash数据类型
服务器·数据库·redis·缓存·微服务·哈希算法
Kookoos8 小时前
Dynamics 365 Finance + Power Automate 自动化凭证审核
运维·自动化·dynamics 365·power automate
ABB自动化11 小时前
for AC500 PLCs 3ADR025003M9903的安全说明
服务器·安全·机器人