原生態(tài)js實現(xiàn)文件上傳功能
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="sunpeiyu文件上傳">
<meta name="author" content="sunpeiyu">
<meta http-equiv="Access-Control-Allow-Origin" content="*">
<title>Document</title>
<style type="text/css">
body {
background-color: white;
}
form {
border: 1px solid red;
}
</style>
<script type="text/javascript">
function uploadFile() {
var fileObj = document.getElementById("fileId").files[0];
var formObj = new FormData();
formObj.append("file", fileObj);
console.log(formObj);
var request = new XMLHttpRequest();
request.open("post", "http://localhost:8091/diverter/file/upload", true);
request.send(formObj);
}
</script>
</head>
<body>
<div>
<p><span>請選擇文件:</span><input type="file" id="fileId"/></p>
<p><input type="submit" value="提交上傳" onclick="uploadFile()"/></p>
</div>
</body>
</html>
springboot后端接收上傳文件并保存在指定的目錄
import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@Slf4j
@RequestMapping("/file")
@RestController
public class FileController {
@GetMapping("/testConn")
public String testConn() {
log.info("=============== 測試成功");
return "=============== 測試成功";
}
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "文件為空乌庶,請選擇一個文件上傳卜范。";
}
try {
// 獲取文件名
String fileName = file.getOriginalFilename();
// 獲取文件的字節(jié)
byte[] bytes = file.getBytes();
String destFilePath = "F:\\temp" + File.separator + fileName;
FileUtil.writeBytes(bytes, destFilePath);
return "文件上傳成功:" + fileName;
} catch (IOException e) {
return "文件上傳失斍钦凇:" + e.getMessage();
}
}
}
從HTTP協(xié)議分析文件上傳功能
上傳文件時坐昙,HTTP協(xié)議使用Content-Type為multipart/form-data磷脯,告知服務端婚惫,該請求為上傳文件。然后請求體報文為kv結(jié)構(gòu)述么,key為file。value為壓縮文件愕掏,采用二進制傳輸度秘。