Python requests post上传文件

参考博客:https://blog.csdn.net/chuangshangbeidong/article/details/112602183

参考博客:https://www.cnblogs.com/xiaobaibailongma/p/12346209.html

django 后端接受views示例:


def upload(request):
    # 首先读取cookies查看用户是否有写文章的权限,如果没有就让他去登录页面login去登录
    user_name = request.COOKIES.get('user_name')
    user_password = request.COOKIES.get('user_password')
    if check_user(user_name, user_password) == False:
        return HttpResponse("please check cookie user_name and user_password!")

    finish = int(request.POST["finish"][0])
    data_folder = str(config.BACKUP_FOLDER)
    mkdir(data_folder)
    upload_temp_folder = config.UPLOAD_TEMP_FOLDER
    mkdir(upload_temp_folder)
    if finish:
        chunk_no = int(request.POST["chunk_no"])
        file_name = request.POST["name"]
        new_file_path = data_folder + "/" + file_name
        new_file = open(new_file_path, "wb")
        for i in range(chunk_no):
            chunk_name = file_name + "_" + str(i)
            chunk_file_path = upload_temp_folder + "/" + chunk_name
            chunk_file = open(chunk_file_path, "rb")
            new_file.write(chunk_file.read())
            chunk_file.close()
            delete_file(config.UPLOAD_TEMP_FOLDER, chunk_file_path)
        new_file.close()
    else:
        file = request.FILES.get("file")
        chunk_no = int(request.POST["chunk_no"])
        file_name = request.POST["name"]
        chunk_name = file_name + "_" + str(chunk_no)
        if file is not None:
            chunk_file_path = upload_temp_folder + "/" + chunk_name
            chunk_file = open(chunk_file_path, "wb")
            chunk_file.write(file.read())
            chunk_file.close()

    return HttpResponse("1")

前端js示例:

// const chunk_size = (1024 * 1024) * 10; // 确定分片大小#}
const chunk_size = (1024 * 1024) * 1; // 确定分片大小#}
// const chunk_size = (1000) * 1; // 确定分片大小
const xmt = new XMLHttpRequest(); // ajax请求
function upload_chunk(index) { // index是上传标记的序列
    const file = document.getElementById("文件").files[0]; // 获取文件
    const {fname, fext} = file.name.split('.'); // 获取文件的名字和拓展名
    const start = index * chunk_size; // 切片的起点
    // 判断起点是否已经超过文件的长度,超过说明已经
    if (start > file.size) {

        const from = new FormData();//定义集合方便后端接收
        from.append("finish", 1);
        from.append("chunk_no", index);
        from.append("chunk_size", chunk_size);
        from.append("name", file.name)
        from.append("file", null);
        xmt.open("post", "/share/upload/", true)//发送请求
        xmt.send(from)//携带集合
        xmt.onreadystatechange = function () {
            if (this.readyState === 4 && this.status === 200) {
                if (this.responseText === "1") {
                    document.getElementById("显示").value = String(((start / file.size)*100).toFixed(3))+"%";//显示上传的进度
                    location.reload();
                }
            }
        }
        return;
    }

    const bool = file.slice(start, start + chunk_size); // slice(分割起点,分割终点)是js切割文件的函数,
    const boolname = fname + index + fext
    const boolfile = new File([bool], boolname) // 把分割后的快转成文件传输
    const from = new FormData();//定义集合方便后端接收

    from.append("finish", 0);
    from.append("chunk_no", index);
    from.append("chunk_size", chunk_size);
    from.append("name", file.name)
    from.append("file", boolfile);
    xmt.open("post", "/share/upload/", true)//发送请求
    xmt.send(from)//携带集合

    xmt.onreadystatechange = function () {
        if (this.readyState === 4 && this.status === 200) {
            if (this.responseText === "1") {
                upload_chunk(++index);
                document.getElementById("显示").value = String(((start / file.size)*100).toFixed(3))+"%";//显示上传的进度
            }
        }
    };
}

python request 模拟上传:

import os
import requests


if __name__ == '__main__':
    url = "http://192.168.1.223:8000/upload/"
    file_path = "D:/1.txt"
    file = open(file_path, "r", encoding='utf-8')
    lines = file.readlines()
    file.close()
    file_data = ""
    for i in range(len(lines)):
        file_data += lines[i]
    headers = {
        "Cookie": "user_name=\"xxx\"; user_password=\"xxx\"",
    }
    data = {
        "finish": 0,
        "chunk_no": 2,
        "chunk_size": len(file_data),
        "name": "1.txt",
    }
    filename = "1.txt"
    files = {
        'file': (filename, file_data, ),
    }
    proxies = {
        'http': "127.0.0.1:8080",
        'https': "127.0.0.1:8080",
    }
    response = requests.post(url, headers=headers, data=data, files=files, proxies=proxies)
    print(response.status_code)
    print(response.text)

java post:


package kuaileshui;


import java.net.*;
import java.io.*;

public class Main {
    public static void main(String[] args) {
        try {
            System.setProperty("http.proxyHost", "127.0.0.1");
            System.setProperty("http.proxyPort", "8080");

            URL url = new URL("http://192.168.1.223:8000/upload/");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "multipart/form-data; boundary=677befb4b757652df892123e54301920");
            con.setRequestProperty("Cookie", "user_name=\"xxx\";user_password=\"xxx\"");

            String boundary = "677befb4b757652df892123e54301920";
            String fileName = "1.txt";
            String fileContent = "This is an example file.";

            String requestBody = "--" + boundary + "\r\n" +
                    "Content-Disposition: form-data; name=\"finish\"\r\n\r\n" +
                    "0\r\n" +
                    "--" + boundary + "\r\n" +
                    "Content-Disposition: form-data; name=\"chunk_no\"\r\n\r\n" +
                    "3\r\n" +
                    "--" + boundary + "\r\n" +
                    "Content-Disposition: form-data; name=\"chunk_size\"\r\n\r\n" +
                    "%d\r\n".formatted(fileContent.length()) +
                    "--" + boundary + "\r\n" +
                    "Content-Disposition: form-data; name=\"name\"\r\n\r\n" +
                    "1.txt\r\n" +
                    "--" + boundary + "\r\n" +
                    "Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n\r\n" +
                    fileContent + "\r\n" +
                    "--" + boundary + "--";

            con.setDoOutput(true);
            OutputStream os = con.getOutputStream();
            os.write(requestBody.getBytes());
            os.flush();
            os.close();

            int responseCode = con.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            System.out.println(response.toString());
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

文章目录