MaZaN
MaZaN

Reputation: 117

Show image from path by python django

I have this code in my django project. it will uploads a file in a path outside django' root in server. now I want an function that can retrive that file and show the client. It's nondirect link and is like http://example.com/uploads/{ID}. now how it's possible. note that uploaded files are image.

def upload(request):
if request.method == 'POST' and request.FILES['file1']:
    myfile = request.FILES['file1']
    fileType = request.GET.get('type',None)
    if fileType==None:
        return json_response(65,400)
    if myfile.size > 5*1024*1000:
        return json_response(85,400)
    elif not (myfile.content_type.startswith('image') or myfile.content_type == 'application/pdf'):
        return json_response(185,400)

    fs = FileSystemStorage('../uploads')
    filename = fs.save(myfile.name, myfile)
    uploaded_file_url = fs.url(filename)
    request.user.file_set.create(name = uploaded_file_url, type = fileType, createdAt = datetime.now())

Upvotes: 1

Views: 102

Answers (1)

Nakul Narayanan
Nakul Narayanan

Reputation: 1452

you can define a view where the id as URL slug. after that you can find the the file path for the corresponding ID to read the file and send the response. here is the code for reading the file from a path and send as HTTP response

with open(valid_image_url, "rb") as f:
     return HttpResponse(f.read(), content_type="image/jpeg")

Upvotes: 1

Related Questions