编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

通过Ajax上传文件给后台接口的方法

wxchong 2024-07-15 09:53:30 开源技术 12 ℃ 0 评论

一、前言

目前web开发流行前后端分离模式,即前端专注于视觉层建设、后端专注于业务逻辑处理。

String或者Integer类型的数据,处理简单直接,一如既往。而file类型就有待商榷了,如何简单处理,是本文的重点。


二、代码实现

1.html

选择/切换文件,都会触发js中的方法。

<el-form-item label="公司logo" :label-width="formLabelWidth">
	<input type="file" @change="uploadCompanyLogo">
</el-form-item>

2.js

js方法中发ajax请求,注意修改请求的配置,类型为 multipart/form-data

uploadCompanyLogo(e) {
    let file = e.target.files[0];
    let param = new FormData();
    param.append("file", file);
    let config = {
    	headers: {
    		"Content-Type": "multipart/form-data"
    	}
    };
    this.$http.post("/file/uploadFile", param, config).then(re => {
    	this.userCompanyAddVO.logo = re.data.data
    	console.log(this.userCompanyAddVO.logo);
    });
},

这里的ajax,借助axios框架,为了方便使用,已先绑定到$http中

3.java接口

这里将传递来的文件,上传到阿里云oss对象存储中(oss非文本重点),注意下后端接口入参类型即可。

import club.linhongcun.recruit.utils.AliyunOSS;
import club.linhongcun.recruit.utils.R;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {

    @PostMapping("/uploadFile")
    public R uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return R.error("请选择文件");
        }
        String filePath = AliyunOSS.getFileUrl(file);
        return R.ok("上传成功", filePath);
    }

}

这里的文件存储,使用企业流行的oss,文件上传成后,返回访问文件的链接

三、其他

ajax请求,可以使用 axios、vue-resource 等方式发起。

文件存储,可以使用 oss、本地、服务器 方式存储等。

无需和本文一致,是不是十分的简单 ~

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表