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

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 "文件上传失败";
        }
    }
}
相关推荐
晨非辰2 小时前
Linux权限管理速成:umask掩码/file透视/粘滞位防护15分钟精通,掌握权限减法与安全协作模型
linux·运维·服务器·c++·人工智能·后端
夜颂春秋3 小时前
jmeter做压力测试
linux·运维·服务器·压力测试
开发者小天9 小时前
python中For Loop的用法
java·服务器·python
绾樘9 小时前
RHCE--基于Nginx的Web服务器配置
运维·服务器·nginx
生活很暖很治愈9 小时前
Linux基础开发工具
linux·服务器·git·vim
打工的小王10 小时前
docker(三)具体项目的部署
运维·docker·容器
步步为营DotNet12 小时前
深度剖析.NET中IHostedService:后台服务管理的关键组件
服务器·网络·.net
一叶星殇12 小时前
.NET WebAPI:用 Nginx 还是 IIS 更好
运维·nginx·.net
Ghost Face...14 小时前
i386 CPU页式存储管理深度解析
java·linux·服务器
LEEE@FPGA14 小时前
zynq 是不是有了设备树,再linux中不需要编写驱动也能控制
linux·运维·单片机