配置:JAVA需要的jar包httpclient4-5-14

python需要的配置:
# # 安装 Windows 兼容版本 # pip install python-magic-bin #pip install flask
JAVA端的代码:
HttpClient4514FileUpload.java
package HttpFlask;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class HttpClient4514FileUpload {
/**
* 基础文件上传方法
* @param url 上传地址
* @param file 要上传的文件
* @return 服务器响应内容
*/
public static String uploadFile(String url, File file) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(url);
// 使用 MultipartEntityBuilder 构建多部分表单数据
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// 添加文件部分
FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY, file.getName());
builder.addPart("file", fileBody); // "file" 是表单字段名
// 添加文本参数(可选)
StringBody commentBody = new StringBody("文件上传示例",
ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8));
builder.addPart("comment", commentBody);
// 构建实体
HttpEntity multipartEntity = builder.build();
httpPost.setEntity(multipartEntity);
// 执行请求
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
// 获取响应实体
HttpEntity responseEntity = response.getEntity();
String responseString = EntityUtils.toString(responseEntity);
// 确保响应实体被完全消费
EntityUtils.consume(responseEntity);
System.out.println("响应状态: " + response.getStatusLine().getStatusCode());
return responseString;
} finally {
response.close();
}
} finally {
httpClient.close();
}
}
}
JAVA测试:HTTPFlask
public class FileHttpFlask {
public static void main(String[] args) {
try {
// 示例1: 基础文件上传
String urlSingle = "http://127.0.0.1:5000/api/upload";
File file = new File("E:\\testWorkPlace\\testrun\\src\\HttpFlask\\upload.txt");
String result = HttpClient4514FileUpload.uploadFile(urlSingle, file);
System.out.println("基础上传结果: " + result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
对应flask代码:
from flask import Flask, request, jsonify, render_template_string, send_file
import os
import uuid
from werkzeug.utils import secure_filename
from datetime import datetime
import magic # 用于更准确的文件类型检测
from datetime import datetime
import time
# # 安装 Windows 兼容版本
# pip install python-magic-bin
app = Flask(__name__)
# 配置文件上传
app.config.update(
UPLOAD_FOLDER='uploads',
MAX_CONTENT_LENGTH=16 * 1024 * 1024, # 16MB
ALLOWED_EXTENSIONS={'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'doc', 'docx', 'zip'},
SECRET_KEY='your-secret-key-here'
)
# 用于存储上传统计信息
upload_stats = {
'total_files': 0,
'total_size': 0,
'last_upload': None
}
# 创建上传目录
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
class FileUploader:
"""文件上传工具类"""
@staticmethod
def allowed_file(filename):
"""检查文件扩展名"""
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']
@staticmethod
def generate_unique_filename(original_filename):
"""生成唯一文件名"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
unique_id = str(uuid.uuid4())[:8]
safe_name = secure_filename(original_filename)
return f"{timestamp}_{unique_id}_{safe_name}"
@staticmethod
def get_file_info(file_path):
"""获取文件详细信息"""
stat = os.stat(file_path)
file_type = "unknown"
try:
# 使用python-magic检测文件类型
import magic
file_type = magic.from_file(file_path, mime=True)
except:
# 备用方案:使用文件扩展名
ext = os.path.splitext(file_path)[1].lower()
file_type = f"application/{ext[1:]}" if ext else "unknown"
return {
'size': stat.st_size,
'created_time': datetime.fromtimestamp(stat.st_ctime).isoformat(),
'modified_time': datetime.fromtimestamp(stat.st_mtime).isoformat(),
'type': file_type
}
@app.route('/api/upload', methods=['POST'])
def api_upload_file():
"""API: 单文件上传"""
try:
if 'file' not in request.files:
return jsonify({'success': False, 'error': '没有文件部分'}), 400
file = request.files['file']
description = request.form.get('description', '')
tags = request.form.get('tags', '')
if file.filename == '':
return jsonify({'success': False, 'error': '没有选择文件'}), 400
if not FileUploader.allowed_file(file.filename):
return jsonify({'success': False, 'error': '不允许的文件类型'}), 400
# 生成唯一文件名
unique_filename = FileUploader.generate_unique_filename(file.filename)
file_path = os.path.join(app.config['UPLOAD_FOLDER'], unique_filename)
# 保存文件
file.save(file_path)
# 获取文件信息
file_info = FileUploader.get_file_info(file_path)
response_data = {
'success': True,
'message': '文件上传成功',
'file': {
'id': unique_filename,
'original_name': file.filename,
'saved_name': unique_filename,
'description': description,
'tags': [tag.strip() for tag in tags.split(',')] if tags else [],
'upload_time': datetime.now().isoformat(),
**file_info
}
}
return jsonify(response_data), 200
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
运行结果:



上传成功!