vue+java文件上传前后端

前端

使用element ui的上传组件

<el-dialog title="上传文件" :visible="uploadDialog" :before-close="closeDialog">
        <el-upload :action="action" :http-request="modeUpload">
          <el-button size="small" type="primary">点击选择文件</el-button>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" :loading="importLoading" @click="imports">{{ importText }}</el-button>
          <el-button @click="uploadDialog = false">取 消</el-button>
        </div>
</el-dialog>
export default {
	data() {
    	return {
    		uploadDialog: false,
      		action: 'https://jsonplaceholder.typicode.com/posts/',
      		mode: {}
    	}
    },
    methods: {
    	modeUpload(item) {
      		this.mode = item.file
    	},
    	imports() {
      		const data = new window.FormData()
      		data.append('anewfile', this.mode)
      		data.append('cid', this.$route.query.cid)
      		this.axios.post('/api/step/imports', data, { headers: { 'Content-Type': 'multipart/form-data' }}).then((response) => {
        		if (response.data) {
          			this.$message({
            			message: '导入成功',
            			type: 'success'
          			})
        		} else {
          			this.$message.error('导入失败')
        		}
      		})
    	}
   	}
}

说明:
在这里插入图片描述
在这里插入图片描述

后端

@RequestMapping("/imports")//导入文件
    public boolean imports(@RequestParam("anewfile") MultipartFile files[], String cid) {
        try {
            String filename = files[0].getOriginalFilename();

在这里插入图片描述
后端可接收到文件参数

后端接口是原有项目提供的,开发了能适配这个接口的前端部分

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是Vue ElementUI和Spring Boot实现文件上传前后端代码示例: 前端代码: ```vue <template> <el-upload class="upload-demo" action="/api/upload" :headers="{ Authorization: 'Bearer ' + token }" :data="{ name: 'avatar' }" :on-success="handleSuccess" :before-upload="beforeUpload"> <el-button slot="trigger" size="small" type="primary">上传文件</el-button> <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> </el-upload> </template> <script> import axios from 'axios'; export default { data() { return { token: '', } }, mounted() { this.token = localStorage.getItem('token'); }, methods: { beforeUpload(file) { const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'; const isLt500K = file.size / 1024 < 500; if (!isJPG) { this.$message.error('上传头像图片只能是 JPG/PNG 格式!'); } if (!isLt500K) { this.$message.error('上传头像图片大小不能超过 500KB!'); } return isJPG && isLt500K; }, handleSuccess(res) { if (res.code === 0) { this.$message.success('上传成功'); } else { this.$message.error('上传失败'); } } } } </script> ``` 后端代码(Spring Boot): ```java @RestController public class FileUploadController { private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class); @Value("${file.upload-dir}") private String uploadDir; @PostMapping("/api/upload") public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("name") String name) { if (file.isEmpty()) { return ResponseEntity.badRequest().body("上传失败,请选择文件"); } String fileName = name + "_" + System.currentTimeMillis() + "_" + file.getOriginalFilename(); try { // 保存文件到指定目录 Path path = Paths.get(uploadDir + fileName); Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { logger.error("文件保存失败", e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件保存失败,请重试"); } logger.info("文件上传成功:{}", fileName); return ResponseEntity.ok().body("文件上传成功"); } } ``` 以上代码示例中,前端代码使用了Vue ElementUI的el-upload组件实现文件上传,设置了文件类型和大小的限制,并通过axios发送文件上传请求,同时在请求头中携带了JWT Token和其他参数。后端代码使用了Spring Boot中的MultipartFile和Files类处理文件上传请求,将上传的文件保存到指定目录中,并返回上传结果和文件信息。其中,上传目录的路径通过@Value注解从配置文件中读取。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值