背景介绍
在Web开发中,文件上传是一项常见且关键的功能。本项目旨在帮助用户上传图片并保存其文件位置,同时显示图片的大小信息,从而实现“图片处理与文件管理”的一体化功能。通过前端文件处理、本地文件系统操作以及图片尺寸计算,项目实现了文件上传、保存与信息展示的完整功能。
思路分析
- 前端文件处理:使用HTML/CSS/JavaScript实现文件上传功能,通过输入框让用户上传图片。
- 本地文件系统操作:利用File API读取上传的图片,保存至本地文件系统,并处理路径。
- 图片尺寸信息显示:通过浏览器的Image API或直接读取文件时的尺寸,展示用户上传的图片大小。
代码实现
1. HTML 文件结构
<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
<style>
body { font-family: Arial, sans-serif; }
input[type="file"] {
display: block;
margin: 10px 0;
padding: 5px;
width: 100%;
}
#result { display: none; margin: 10px; }
</style>
</head>
<body>
<input type="file" id="imageInput" accept="image/*" />
<div id="result" style="display: none;"></div>
<script>
const imgEl = document.getElementById('result');
const input = document.getElementById('imageInput');
input.addEventListener('change', function () {
const file = this.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function (e) {
const img = new Image();
img.src = e.target.result;
img.onload = function () {
const width = img.width;
const height = img.height;
imgEl.textContent = `宽 ${width}px,高 ${height}px`;
};
};
reader.readAsDataURL(file);
}
});
</script>
</body>
</html>
2. Python 实现(使用Flask框架)
由于项目独立运行,可部署至本地服务器并运行。以下是使用Flask的实现代码:
from flask import Flask, request, render_template_string
app = Flask(__name__)
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['image']
file_path = 'uploads/' + file.filename
file.save(file_path)
return render_template_string(
"""
<div>
<h2>图片尺寸:宽 ${width}px,高 ${height}px</h2>
文件路径:/uploads/<%= file.filename %>
</div>
"""
)
if __name__ == '__main__':
app.run(debug=True)
总结
本项目通过前端文件处理和后端本地文件系统操作的结合,实现了图片上传、保存及尺寸信息的展示功能。通过HTML/CSS实现用户界面的交互,借助Python的Flask框架处理上传逻辑,确保项目可部署并运行。这一实现不仅满足了前端文件处理的需求,也为后续的文件管理功能奠定了基础。