0

Is there a way to copy a file in request.FILES to a remote location such as 100.100.1.100/home/dbadmin/EncFiles in Django? I have consulted from this and this questions but I don't need to log on to the server to copy file.

I have a simple file in my memory that I need to send to another server. How do I do that?

Tahreem Iqbal
  • 985
  • 6
  • 17
  • 43
  • I think InMemoryUploadedFile class in Django may be useful for you. Because my code context is different with yours , I can't give you the example code, but you can do try it – Hayden Dec 12 '17 at 08:31
  • can you give me the code that takes a normal file so i can see if i can change that for my purpose? – Tahreem Iqbal Dec 12 '17 at 09:14

2 Answers2

0

The comment seems to can't have contain formated code, so I have to use answer to reply:

def crop_avatar(file_path,size):

    avatar_format = get_image_format(os.path.splitext(file_path)[1])
    file_format = avatar_format.split('/')[1]
    avatar_filename = get_avatar_filename(file_path)

    image_file = default_storage.open(file_path)
    image = Image.open(image_file)
    if image.mode not in ('L', 'RGB'):
        image = image.convert('RGB')
    width,height = image.size

    crop_ratio = float(200)/(size[2]-size[0])
    ratio = float(480)/width * crop_ratio

    width  = int(width  * ratio)
    height = int(height * ratio)

    left = int(size[0] * crop_ratio)
    top =  int(size[1] * crop_ratio)

    crop_image = image.resize((width,height),Image.ANTIALIAS)


    crop_image = crop_image.crop((left,top,left+200,top+200))

    avatar_io = BytesIO()#this is for default_storage using.
    crop_image.save(avatar_io, format=file_format)

    avatar = InMemoryUploadedFile(
        avatar_io,
        None,
        avatar_filename,
        avatar_format,
        len(avatar_io.getvalue()),
        None)
    avatar.seek(0)
    saved_path =  default_storage.save(avatar_filename, avatar)
    image_file.close()
    default_storage.delete(file_path)


    return saved_path
Hayden
  • 449
  • 4
  • 13
0

It turned out to be very simple in the end. I created two users on both computers with same credentials, gave rights to the folder to this user and used the following code to copy file. Oh and the computers where connected by LAN.

serverPath = r"\\192.111.111.111/myFolder"

if os.path.exists(serverPath):
    for key in request.FILES:
        fileName = request.FILES[key].name
        d, filePath = tempfile.mkstemp(suffix=request.FILES[key].name, dir=serverPath)

        with open(filePath, 'wb') as outFile:
            shutil.copyfileobj(request.FILES[key], outFile)
Tahreem Iqbal
  • 985
  • 6
  • 17
  • 43