1

代码:

company = Company.objects.get(pk=pk)

    if request.POST:
        company_name = request.POST['company_name']

        company_logo = request.FILES['company_logo']
        fs = FileSystemStorage(location='/home/ubuntu/mywebsite/media/company/' + str(company.pk) + '/')
        filename = fs.save(company_logo.name, company_logo)
        uploaded_file_url = fs.url(filename)

fs.url返回:/media/thefilename.png这是错误的......显然该.url方法没有考虑到您将location属性设置为什么?

如何确保返回正确的路径?

4

3 回答 3

2

遇到了同样的问题,所以要完成@alfonso.kim 所说的,我必须同时指定base_urland location。用你的代码它会是这样的

company = Company.objects.get(pk=pk)

    if request.POST:
        company_name = request.POST['company_name']

        company_logo = request.FILES['company_logo']

        dir_storage = '/home/ubuntu/mywebsite/media/company/' + str(company.pk) + '/'
        fs = FileSystemStorage(location=dir_storage , base_url = dir_storage )
        filename = fs.save(company_logo.name, company_logo)
        uploaded_file_url = fs.url(filename)

旧线程,但希望它会有所帮助

于 2019-02-22T10:13:42.800 回答
0

根据文档

base_url

提供存储在此位置的文件的 URL。默认为您的 MEDIA_URL 设置的值。

您正在设置存储的位置,而url默认为MEDIA_URL. 如果您想提供用户上传的文件,请查看此处此处

希望这可以帮助。

于 2017-05-29T23:37:44.603 回答
0
            //settings.py
            MEDIA_URL = '/media/'
            MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
            //end of settings.py

            //this one is for save the image to preferred directory
            logoRoot = os.path.join(settings.MEDIA_ROOT, 'images/')

            //this is for accessing the image after you save it
            logo_url = os.path.join(settings.MEDIA_URL, 'images/')

            logoRoot=logoRoot.replace("\\","/")


            fs = FileSystemStorage(location=logoRoot)
            filename = fs.save(company_logo.name, company_logo)


            //image url, don't use fs.url(filename) to get image url instead use code 
            below

            uploaded_file_url = logo_url+filename
于 2019-11-11T19:43:11.030 回答