无法打开文件,因为它是空的

时间:2016-02-08 13:55:44

标签: python flask

我想从请求中上传2张图片。我正在创建一个函数,它接受JCalendar作为参数并保存两个图像。

功能是:

request.files

当我尝试保存图像时。它保存得当。 def store_offer_images(files, **service_response): """ Stores the Images """ create_diretory_if_not_exist() lrg_img, sml_img = files.get('detail_image'), files.get('listing_image') lrg_img_filename = service_response.get('content').get('offerId') + ".png" sml_img_filename = service_response.get('content').get('offerId') + ".png" sml_img.save( os.path.join(config.NORMAL_FILE_UPLOAD_FOLDER, sml_img_filename)) lrg_img.save( os.path.join(config.LARGE_FILE_UPLOAD_FOLDER, lrg_img_filename)) filesrequest.filesservice_response

当我想在Finder(OS GUI窗口)中打开图像时,我收到了消息:

kwargs

enter image description here

如何上传图片?

修改
当我在pdb中查看文件时,以下是响应:

The file “b516f2dca72e4f559c3a72a1f48727a9.png” could not be opened because it is empty.

模拟我的请求数据的模型是:

(pdb) files.get('detail_image')
(pdb) <FileStorage: u'python-640x444.png' ('image/png')>

import datetime from app_config import AppConfig class Offer(object): """ Offer Details """ def __init__(self, form): self.REST_API_TIME_FORMAT = AppConfig().REST_API_TIME_FORMAT self.title = form.get('title') self.start_date = form.get('startsOn') + ' 00:00' self.end_date = form.get('endsOn') + ' 23:59' self.short_description = form.get('shortDescription') self.long_description = form.get('longDescription') self.outlets = form.getlist('outlets') self.offer_value = form.get('offerValue') self.offer_old_value = form.get('oldValue') self.currency = form.get('currency') def add_offer_body(self): """ Return the request body in json format """ outlets_list = [] for i in self.outlets: outlets_list.append({'code': i}) starts_on_date = datetime.datetime.strptime( self.start_date, '%d/%m/%Y %H:%M') ends_on_date = datetime.datetime.strptime( self.end_date, '%d/%m/%Y %H:%M') body = { "outlets": outlets_list, "title": self.title, "shortDescription": self.short_description, "longDescription": self.long_description, "endsOn": ends_on_date.strftime(self.REST_API_TIME_FORMAT), "startsOn": starts_on_date.strftime(self.REST_API_TIME_FORMAT), "isActive": "true", } if self.offer_value is not u'': body['offerValue'] = { "value": self.offer_value, "currency": self.currency } if self.offer_old_value is not u'': body["offerOldValue"] = { "value": self.offer_old_value, "currency": self.currency } return body def __repr__(self): return self.title 是:

views.py

HTML是:

@portal.route('/admin/offers/add', methods=['POST'])
def add_offer():
    """
    Return status of added offer
    """
    offer = Offer(request.form)
    if controller.valid_content(request.files):
        service_response = controller.add_offer(offer)
        if 'errors' in service_response:
            message = str(service_response.get('errors')[0].get('message'))
            flash("Adding Offer Failed.!! " + message)
            current_app.logger.error(
                'Offer adding failed with details' + str(request.form))
            return redirect(url_for('portal.list_running_offers'))
        else:
            controller.store_offer_images(request.files, **service_response)
            current_app.logger.info('User added a offer successfully.')
            flash("Offer added successfully..!!")
            return redirect(url_for('portal.list_running_offers'))
    else:
        flash("Please upload all Images of mentioned Resolution.!!")
        return render_template(
            'addoffer.jinja', body=offer.add_offer_body(), help=help_messages)

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。它发生了,因为如果我对Image执行任何操作,它将最后移动我的指针,所以当你保存图像时,它开始将图像保存在指针所在的位置,这是最后一次。所以保存的图像是空的。

现在要解决这个问题,我只需将指针移到开头即可。以下是我所做的示例代码:

if img is not None and img.filename != u'':
            img.seek(0, os.SEEK_END)
            size = img.tell()
            imgs = Image.open(img)
            res = imgs.size
            img.seek(0)