在Springboot里面实现文件的上传服务
思路:首先ajax那边提交请求上传文件,然后后台进行处理,因为springboot打包之后是个jar包部署,所以希望是在跟jar包同级目录下面创建一个file目录专门来存放文件。
注:这里面使用了Path以及Paths接口工具来做文件的处理,非常的好用以及高效,如果又不懂的请网上查询了解相应的用法等。
下面直接贴代码
@PostMapping("/api/upload/multi")
public ResponseEntity<?> uploadFileMulti(
@RequestParam("extraField") String extraField,
@RequestParam("files") MultipartFile[] uploadfiles) {
logger.debug("Multiple file upload!");
String uploadedFileName = Arrays.stream(uploadfiles).map(x -> x.getOriginalFilename())
.filter(x -> !StringUtils.isEmpty(x)).collect(Collectors.joining(" , "));
if (StringUtils.isEmpty(uploadedFileName)) {
return new ResponseEntity("please select a file!", HttpStatus.OK);
}
try {
saveUploadedFiles(Arrays.asList(uploadfiles));
} catch (IOException e) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity("Successfully uploaded - "
+ uploadedFileName, HttpStatus.OK);
}
//save file
private void saveUploadedFiles(List<MultipartFile> files) throws IOException {
for (MultipartFile file : files) {
if (file.isEmpty()) {
continue; //next pls
}
//String appPath = Paths.get(".").getFileSystem()
byte[] bytes = file.getBytes();
//Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
//Path path = Paths.get("../uploadFileTest/"+file.getOriginalFilename());
Path path = Paths.get("../uploadFileTest/");
if(Files.notExists(path)){
Files.createDirectory(path);
}
Path storagePath = Paths.get("../uploadFileTest/"+file.getOriginalFilename());
Files.write(storagePath, bytes);
}
}
因为存放的是相对路径的上一级,所以这面使用了../来到上一级。
下面是html以及ajax
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Spring Boot - Multiple file upload example - AJAX</h1>
<form method="POST" enctype="multipart/form-data" id="fileUploadForm">
<input type="text" name="extraField"/><br/><br/>
<input type="file" name="files"/><br/><br/>
<input type="file" name="files"/><br/><br/>
<input type="submit" value="Submit" id="btnSubmit"/>
</form>
<h1>Ajax Post Result</h1>
<pre>
<span id="result"></span>
</pre>
<script type="text/javascript"
src="webjars/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
js
$(document).ready(function () {
$("#btnSubmit").click(function (event) {
//stop submit the form, we will post it manually.
event.preventDefault();
fire_ajax_submit();
});
});
function fire_ajax_submit() {
// Get form
var form = $('#fileUploadForm')[0];
var data = new FormData(form);
data.append("CustomField", "This is some extra data, testing");
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "/api/upload/multi",
data: data,
//http://api.jquery.com/jQuery.ajax/
//https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
processData: false, //prevent jQuery from automatically transforming the data into a query string
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
$("#result").text(data);
console.log("SUCCESS : ", data);
$("#btnSubmit").prop("disabled", false);
},
error: function (e) {
$("#result").text(e.responseText);
console.log("ERROR : ", e);
$("#btnSubmit").prop("disabled", false);
}
});
}
有什么问题可以底下留言,我看到会及时回复。一起学习一起进步。