python 上传文件 上传图片到 服务器
import requests
import os
from datetime import datetime
class ImageUploader:
def __init__(self, base_url="http://localhost/api/xcx/user/uploadimage"):
self.base_url = base_url
def upload_image(self, openid, image_path, image_type=None):
"""
向指定接口上传图片文件
参数:
openid (str): 用户唯一标识
image_path (str): 图片文件路径
image_type (int, optional): 图片类型标识
base_url (str): 接口地址
返回:
dict: 接口返回的JSON数据
异常:
FileNotFoundError: 当图片文件不存在时
ValueError: 当文件类型不支持时
Exception: 当上传过程中发生错误时
"""
# 检查文件是否存在
if not os.path.exists(image_path):
raise FileNotFoundError(f"文件不存在: {image_path}")
# 检查文件类型
allowed_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp']
ext = os.path.splitext(image_path)[1].lower()
# if ext not in allowed_extensions:
# raise ValueError(f"不支持的文件类型: {ext},支持的格式: {', '.join(allowed_extensions)}")
try:
# 读取文件内容到内存,避免文件关闭问题
with open(image_path, 'rb') as file:
file_content = file.read()
# 获取文件名和MIME类型
filename = os.path.basename(image_path)
mime_type = self._get_mime_type(ext)
# 准备文件数据
files = {
'file': (filename, file_content, mime_type)
}
# 准备表单数据
data = {
'openid': openid,
# 'type': image_type
}
print(f"正在上传文件: {filename}, 大小: {len(file_content)} 字节")
# 发送POST请求
response = requests.post(
url=self.base_url,
files=files,
data=data,
timeout=30
)
# 检查响应状态
response.raise_for_status()
# 返回JSON响应
return response.json()
except requests.exceptions.ConnectionError:
raise Exception("无法连接到服务器,请检查网络连接和服务器地址")
except requests.exceptions.Timeout:
raise Exception("请求超时,请稍后重试")
except requests.exceptions.RequestException as e:
raise Exception(f"请求失败: {str(e)}")
except Exception as e:
raise Exception(f"上传过程中发生错误: {str(e)}")
def _get_mime_type(self, ext):
"""根据文件扩展名获取MIME类型"""
mime_map = {
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.png': 'image/png',
'.gif': 'image/gif',
'.bmp': 'image/bmp'
}
return mime_map.get(ext, 'application/octet-stream')
def batch_upload(self, openid, image_paths, image_type=None):
"""
批量上传多张图片
参数:
openid (str): 用户唯一标识
image_paths (list): 图片文件路径列表
image_type (int, optional): 图片类型标识
"""
results = []
for image_path in image_paths:
try:
result = self.upload_image(openid, image_path, image_type)
results.append({
'file': image_path,
'success': True,
'result': result
})
except Exception as e:
results.append({
'file': image_path,
'success': False,
'error': str(e)
})
return results
def main():
"""主函数示例"""
uploader = ImageUploader()
try:
# 示例参数 - 请根据实际情况修改
openid = "user12345"
image_path = "test.html" # 替换为实际图片路径
image_type = 1
# 单文件上传
result = uploader.upload_image(openid, image_path, image_type)
print("上传成功,服务器返回:", result)
# 批量上传示例
# image_paths = ["/path/to/image1.jpg", "/path/to/image2.png"]
# batch_results = uploader.batch_upload(openid, image_paths, image_type)
# print("批量上传结果:", batch_results)
except Exception as e:
print("上传失败:", str(e))
if __name__ == "__main__":
main()小程序上传图片 到服务代码
onChooseImage: function (e) {
var this_ = this;
var header = {
"Content-Type": "multipart/form-data"
};
var openid = this.data.openid;
var formData = {
'openid': openid,
type: 1
};
var tempFilePath = e.detail.avatarUrl;
console.log("tempFilePath:",tempFilePath);//tempFilePath: http://tmp/YheATlYhktGrab7ba0dfc9992fff8e07902a8fd1b22f.jpeg
uploadFile2(baseURL + "/api/xcx/user/uploadimage", tempFilePath, "image", header, formData).then(res => {
wx.hideLoading()
var result = JSON.parse(res.data); //
console.log(result.url);
this_.load_xcx_user();
//更新用户 头像
})
},
export function uploadFile2(url, filePath, name, header, formData) {
//使用promise最大的好处是 防止出现回调地狱
return new Promise((resolve, reject) => {
wx.uploadFile({
url: url,
filePath: filePath,
name: name,
header: header,
formData: formData,
success: function (res) {
resolve(res);
},
fail: function (err) {
reject(err)
}
})
})
}springboot 接口代码
/**
* 更新 用户头像。 接受的有openid
* /api/xcx/user/uploadimage
* @RequestParam("file") MultipartFile file,
* 这个接口2个地方 使用。
*/
@ResponseBody
@RequestMapping("/uploadimage")
public JSONObject uploadimage( @RequestParam("openid") String openid,
@RequestParam(value = "type", required = false) Integer type,
HttpServletRequest request)throws Exception {
JSONObject result = new JSONObject();
//获取文件需要上传到的路径
String webPath=request.getServletContext().getRealPath("");
System.out.println("openid:"+openid);//
System.out.println("type:"+type);//
XcxUser xcxUser =null;
if(type!=null){
//上传加修改头像 一起操作。 提交获取 user
xcxUser = xcxUserService.findByOpenid(openid);
}
String filePath= "/static/xcx_upload/xcx_user_head/"+ DateUtil.formatDate(new Date(), "yyyyMMdd")+"/";
FileUtil.makeDirs(webPath+filePath);
request.setCharacterEncoding("utf-8"); //设置编码
try {
StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
Iterator<String> iterator = req.getFileNames();
while (iterator.hasNext()) {
HashMap<String, Object> res = new HashMap<String, Object>();
MultipartFile file = req.getFile(iterator.next());
// 获取文件名
String fileNames = file.getOriginalFilename();
int split = fileNames.lastIndexOf(".");
//获取上传文件的后缀
String extName = fileNames.substring(split + 1, fileNames.length());
// 判断后缀名是否在允许的数组中
boolean isAllowed = Arrays.asList(suffixArray).contains(extName);
System.out.println(isAllowed);
//false是不在名单中 true是在 名单中
if(isAllowed){
return null;
}
//申明UUID
String uuid = UUID.randomUUID().toString().replace("-", "");
//组成新的图片名称
String newName = uuid + "." + extName;
System.out.println(newName);
String destPath = webPath+filePath + newName;
//真正写到磁盘上
File file1 = new File(destPath);
OutputStream out = new FileOutputStream(file1);
out.write(file.getBytes());
res.put("url", destPath);
result.put("url", filePath+ newName);
//更新头像,
if(type!=null){
//判断 路径 有没有包含 xcx_upload 如果有就删除头像吧。
if(xcxUser.getHeadimgurl().contains("upload")){
FileUtil.deleteFile(webPath+xcxUser.getHeadimgurl());
}
//删除后 再更新。
xcxUser.setHeadimgurl(filePath+ newName);
xcxUserService.updateById(xcxUser);
}
out.close();
}
} catch (Exception e) {
}
return result;
}站长微信:xiaomao0055
站长QQ:14496453