Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django file upload doesn't work: f.read() returns ''

I'm trying to upload and parse json files using django. Everything works great up until the moment I need to parse the json. Then I get this error:

No JSON object could be decoded: line 1 column 0 (char 0)

Here's my code. (I'm following the instructions here, and overwriting the handle_uploaded_file method.)

def handle_uploaded_file(f, collection):
#  assert False, [f.name, f.size, f.read()[:50]]
  t = f.read()
  for j in serializers.deserialize("json", t):
    add_item_to_database(j)

The weird thing is that when I uncomment the "assert" line, I get this:

[u'myfile.json', 59478, '']

So it looks like my file is getting uploaded with the right size (I've verified this on the server), but the read command seems to be failing entirely.

Any ideas?

like image 858
Abe Avatar asked Dec 01 '25 21:12

Abe


1 Answers

I've seen this before. Your file has length, but reading it doesn't. I'm wondering if it's been read previously... try this:

f.seek(0)
f.read()
like image 153
Jason Goldstein Avatar answered Dec 03 '25 15:12

Jason Goldstein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!