import requests
from urllib.parse import urlparse
def upload_file(pre_signed_url, file_path):
try:
# 设置请求头
headers = {
"X-bailian-extra": "NTQ0MzUyMDc2MzgzNzcwMw==",
"Content-Type": "application/pdf"
}
# 读取文件并上传
with open(file_path, 'rb') as file:
response = requests.put(pre_signed_url, data=file, headers=headers)
# 检查响应状态码
if response.status_code == 200:
print("File uploaded successfully.")
else:
print(f"Failed to upload the file. ResponseCode: {response.status_code}")
except Exception as e:
print(f"An error occurred: {str(e)}")
def upload_file_link(pre_signed_url, source_url_string):
try:
# 设置请求头
headers = {
"X-bailian-extra": "NTQ0MzUyMDc2MzgzNzcwMw==",
"Content-Type": "application/pdf"
}
# 获取源文件
source_response = requests.get(source_url_string)
if source_response.status_code != 200:
raise RuntimeError("Failed to get source file.")
# 上传文件
response = requests.put(pre_signed_url, data=source_response.content, headers=headers)
# 检查响应状态码
if response.status_code == 200:
print("File uploaded successfully.")
else:
print(f"Failed to upload the file. ResponseCode: {response.status_code}")
except Exception as e:
print(f"An error occurred: {str(e)}")
if __name__ == "__main__":
pre_signed_url_or_http_url = "https://bailian-datahub-data-origin-prod.oss-cn-beijing.aliyuncs.com/1005426495169178/10036719/2070f50790a8482b985c36691cc7b093.1725003661081.pdf?Expires=1725004261&OSSAccessKeyId=LTAI5tKzNnKPFwCJSCpx****&Signature=OPgdNJ%2BMU%2FLtRjBzXiUjVYQsphw%3D"
# 上传网络文件
file_path = "https://test-lxg-quanxian.oss-cn-beijing.aliyuncs.com/%E6%B5%8B%E8%AF%95-%E6%96%B0%E9%97%BB.pdf?Expires=1725010144&OSSAccessKeyId=TMP.3KfyS1Pyk8YQ4F9fTYGhVpRXe9QJbRfFrKiP6ujzXWr2zu77Pmb8syzh8nLBZkSUskbdLd9KsNTC6RpeUt8pzScnJ9****&Signature=4jxj7hfJTnHWeM49dcd9sWWkXWs%3D"
upload_file_link(pre_signed_url_or_http_url, file_path)
# 上传本地文件
# file_path = "/Users/legolas/Downloads/测试-新闻.pdf"
# upload_file(pre_signed_url_or_http_url, file_path)
//代码仅为示例代码,未进行各类测试,请勿在生产环境直接使用
import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class UploadFile{
public static void uploadFile(String preSignedUrl, String filePath) {
HttpURLConnection connection = null;
try {
// 创建URL对象
URL url = new URL(preSignedUrl);
connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为PUT,预签名URL默认用于PUT操作进行文件上传
connection.setRequestMethod("PUT");
// 允许向connection输出,因为这个连接是用于上传文件的
connection.setDoOutput(true);
// 设置请求头,这里设置ApplyFileUploadLease接口返回的Data.Param.Headers中的参数
connection.setRequestProperty("X-bailian-extra", "NTQ0MzUyMDc2MzgzNzcwMw==");
connection.setRequestProperty("Content-Type", "application/pdf");
// 读取文件并通过连接上传
try (DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
FileInputStream fileInputStream = new FileInputStream(filePath)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
outStream.flush();
}
// 检查响应代码
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 文件上传成功处理
System.out.println("File uploaded successfully.");
} else {
// 文件上传失败处理
System.out.println("Failed to upload the file. ResponseCode: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
public static void uploadFileLink(String preSignedUrl, String sourceUrlString) {
HttpURLConnection connection = null;
try {
// 创建URL对象
URL url = new URL(preSignedUrl);
connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为PUT,预签名URL默认用于PUT操作进行文件上传
connection.setRequestMethod("PUT");
// 允许向connection输出,因为这个连接是用于上传文件的
connection.setDoOutput(true);
// 设置请求头,这里设置ApplyFileUploadLease接口返回的Data.Param.Headers中的参数
connection.setRequestProperty("X-bailian-extra", "NTQ0MzUyMDc2MzgzNzcwMw==");
connection.setRequestProperty("Content-Type", "application/pdf");
URL sourceUrl = new URL(sourceUrlString);
HttpURLConnection sourceConnection = (HttpURLConnection) sourceUrl.openConnection();
// 设置请求方法为GET
sourceConnection.setRequestMethod("GET");
// 获取响应码,200表示请求成功
int sourceFileResponseCode = sourceConnection.getResponseCode();
// 读取文件并通过连接上传
if (sourceFileResponseCode != HttpURLConnection.HTTP_OK){
throw new RuntimeException("Failed to get source file.");
}
try (DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
InputStream in = new BufferedInputStream(sourceConnection.getInputStream())) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
outStream.flush();
}
// 检查响应代码
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 文件上传成功处理
System.out.println("File uploaded successfully.");
} else {
// 文件上传失败处理
System.out.println("Failed to upload the file. ResponseCode: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
public static void main(String[] args) {
String preSignedUrlOrHttpUrl = "https://bailian-datahub-data-origin-prod.oss-cn-beijing.aliyuncs.com/1005426495169178/10036719/2070f50790a8482b985c36691cc7b093.1725003661081.pdf?Expires=1725004261&OSSAccessKeyId=LTAI5tKzNnKPFwCJSCpx****&Signature=OPgdNJ%2BMU%2FLtRjBzXiUjVYQsphw%3D";
//以下代码是上传网络文件,请将filepath替换为自己的网络文件路径
String filePath = "https://test-lxg-quanxian.oss-cn-beijing.aliyuncs.com/%E6%B5%8B%E8%AF%95-%E6%96%B0%E9%97%BB.pdf?Expires=1725010144&OSSAccessKeyId=TMP.3KfyS1Pyk8YQ4F9fTYGhVpRXe9QJbRfFrKiP6ujzXWr2zu77Pmb8syzh8nLBZkSUskbdLd9KsNTC6RpeUt8pzScnJ9****&Signature=4jxj7hfJTnHWeM49dcd9sWWkXWs%3D";
uploadFileLink(preSignedUrlOrHttpUrl,filePath);
//以下代码是上传本地文件
//String filePath = "/Users/legolas/Downloads/测试-新闻.pdf";
//uploadFile(preSignedUrlOrHttpUrl, filePath);
}
}