当前位置: 首页> 汽车> 行情 > 关于前端如何上传文件/服务器如何接受并保存

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

时间:2025/7/9 1:07:43来源:https://blog.csdn.net/weixin_60246228/article/details/141002061 浏览次数: 0次

1.前端代码

<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.后端代码

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 "文件上传失败";}}
}

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: