前端代码展示
<template>
<div>
<div>
<div id="result"></div>
<h1>{{ msg }}</h1>
<form>
<input type="file" @change="getFile($event)" />
<button
class="button button-primary button-pill button-small"
@click="submit($event)"
>
提交
</button>
</form>
</div>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "test",
data() {
return {
param: {},
file: "",
};
},
created() {
},
methods: {
getFile: function (event) {
this.file = event.target.files[0];
console.log(this.file);
},
submit: function (event) {
//阻止元素发生默认的行为
event.preventDefault();
let formData = new FormData();
formData.append("file", this.file);
axios
.post("http://localhost:9000/upload/singlefile", formData)
.then(function (response) {
alert(response.data);
console.log(response);
window.location.reload();
})
.catch(function (error) {
alert("上传失败");
console.log(error);
window.location.reload();
});
},
},
};
</script>
<style scoped>
h1,
h2 {
font-weight: normal;
}
.button-pill {
border-radius: 200px;
}
.button-primary,
.button-primary-flat {
background-color: #1b9af7;
border-color: #1b9af7;
color: #fff;
}
.button {
color: #fff;
background-color: #1b9af7;
border-color: #eee;
font-size: 16px;
font-family: "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial,
"Lucida Grande", sans-serif;
text-decoration: none;
text-align: center;
line-height: 40px;
height: 40px;
padding: 0 40px;
margin: 0;
display: inline-block;
appearance: none;
cursor: pointer;
border: none;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-transition-property: all;
transition-property: all;
-webkit-transition-duration: 0.3s;
transition-duration: 0.3s;
}
.button-small {
font-size: 12px;
height: 30px;
line-height: 30px;
padding: 0 30px;
}
</style>
后端代码展示 直接创建一个
FileUploadController.java用于和前端交互 代码如下
package com.sport.sports.controller;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
/**
* Created by IntelliJ IDEA.
*
* @author xiaolan
* @date 2022/1/21
**/
@RestController
@RequestMapping("/upload")
@CrossOrigin
public class FileUploadController {
@Value("${prop.upload-folder}")
private String UPLOAD_FOLDER;
// private Logger logger = LoggerFactory.getLogger(FileUploadController.class);
@PostMapping("/singlefile")
public Object singleFileUpload(MultipartFile file) {
// logger.debug("传入的文件参数:{}", JSON.toJSONString(file, true));
if (Objects.isNull(file) || file.isEmpty()) {
// logger.error("文件为空");
return "文件为空,请重新上传";
}
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOAD_FOLDER + file.getOriginalFilename());
//如果没有files文件夹,则创建
if (!Files.isWritable(path)) {
Files.createDirectories(Paths.get(UPLOAD_FOLDER));
}
//文件写入指定路径
Files.write(path, bytes);
System.out.println(path);
// logger.debug("文件写入成功...");
return "文件上传成功";
} catch (IOException e) {
e.printStackTrace();
return "后端异常...";
}
}
}
其中
@Value("${prop.upload-folder}")
在application.yml中配置 如下列出完整的配置
# mysql
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ca_new?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8
username: root
password: 123456
#设置最大上传大小为10Mb
http:
multipart:
max-file-size: 50Mb
max-request-size: 50MB
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.sport.sports.Bean
server:
port: 9000
# port: 8093
#文件存储路径
prop:
# upload-folder: files/
upload-folder: "D://files/"
最终完成前后端分离的文件上传