分析文件上传

2024-06-14  本文已影响0人  sunpy

原生态js实现文件上传功能

<!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();
            // 获取文件的字节
            byte[] bytes = file.getBytes();
            String destFilePath = "F:\\temp" + File.separator + fileName;
            FileUtil.writeBytes(bytes, destFilePath);
            return "文件上传成功:" + fileName;
        } catch (IOException e) {
            return "文件上传失败:" + e.getMessage();
        }
    }
}

从HTTP协议分析文件上传功能

上传文件时,HTTP协议使用Content-Type为multipart/form-data,告知服务端,该请求为上传文件。然后请求体报文为kv结构,key为file。value为压缩文件,采用二进制传输。

上一篇 下一篇

猜你喜欢

热点阅读