ajax上传file文件

辛成周
2023-12-01

前端

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="js/jquery.min.js"></script>
	</head>
	<body>
		<form id="uploadForm" enctype="multipart/form-data">
		    <input id="file" type="file" name="file"/>
		    <button id="upload" type="button">upload</button>
		</form>
	</body>
	<script>
	$("#upload").click(function () {
	            $.ajax({
	                url: 'http://localhost:8081/upload0',
	                type: 'POST',
	                cache: false,
	                data: new FormData($('#uploadForm')[0]),
	                processData: false,
	                contentType: false,
	                success: function (data) {
						console.log(data)
	                    alert(data.msg)
	                }
	            }).fail(function (res) {
					console.log(res)
	                alert("系统错误")
	            });
	        });
	</script>
</html>

后端

注意跨域问题

 /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @CrossOrigin
    @RequestMapping(path = "/upload0", method = {RequestMethod.POST})
    public Result upload0(MultipartFile file) {
        if (!file.isEmpty()) {
            String upload = FileUtil.fileUpload(file);
            System.out.println(upload);
            return  Result.init(200, "上传成功", null);
        }
        return  Result.init(-200, "上传失败", null);
    }

https://www.cnblogs.com/suflowers1700218/p/14230852.html

 类似资料: