You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask中如何将文件有效保存至指定目录?文件存为0KB求助

Flask上传文件保存为0KB的解决方法

问题根源

你代码中调用dcmread(file, force=True)读取上传的文件对象时,已经将文件指针移动到了文件末尾。后续执行file.save()时,会从当前指针位置开始写入,因此生成的文件大小为0KB。

两种解决方式

方式1:先保存文件,再读取处理DICOM内容

先把上传的文件保存到目标路径,再从本地文件读取DICOM数据,这样不会影响文件保存的完整性:

@app.route("/droid",methods=['GET','POST'])
def cloud_Upload():                                  
    if 'file' not in request.files:
        flash('No file part')
        return redirect('/home')
    file = request.files['file']
    if file.filename == '':
        flash('No image selected for uploading')
        return redirect('/home')
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        path = 'C:/Users/malvinjohnny/Desktop/project_server/azure/'
        # 确保目标目录存在,直接创建path目录而非父目录
        os.makedirs(path, exist_ok=True)
        save_path = os.path.join(path, filename)
        # 先保存文件
        file.save(save_path)
        # 再从本地文件读取DICOM数据
        dicom_file = dcmread(save_path, force=True)
        dicom_file_metadata = dir(dicom_file)
        attributes = dir(dicom_file)
    return render_template('droid.html')

方式2:读取DICOM后重置文件指针到开头

如果不想先保存文件,可以在读取DICOM后,将文件指针重置到起始位置,再执行保存操作:

@app.route("/droid",methods=['GET','POST'])
def cloud_Upload():                                  
    if 'file' not in request.files:
        flash('No file part')
        return redirect('/home')
    file = request.files['file']
    if file.filename == '':
        flash('No image selected for uploading')
        return redirect('/home')
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        # 读取DICOM数据
        dicom_file = dcmread(file, force=True)
        dicom_file_metadata = dir(dicom_file)
        attributes = dir(dicom_file)
        # 重置文件指针到文件开头
        file.seek(0)
        path = 'C:/Users/malvinjohnny/Desktop/project_server/azure/'
        os.makedirs(path, exist_ok=True)
        # 保存文件
        file.save(os.path.join(path, filename))
    return render_template('droid.html')

额外注意点

原代码中os.makedirs(os.path.dirname(path), exist_ok=True)存在逻辑问题:path已经是目标目录(azure/),os.path.dirname(path)会返回它的父目录(project_server/),直接使用os.makedirs(path, exist_ok=True)可以确保目标目录azure/存在,更符合需求。

内容的提问来源于stack exchange,提问作者John Mwanza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 20:45:35