Java sets file permissions when writing files

       Recently, when I used the Nginx proxy to directly read images from the hard disk, I found that Nginx does not have the permission to read the file. This is because the owner of the file is root and the running user of Nginx is www-data, so the image cannot be accessed. When the program stores images, it defaults to root, so you need to set the file permissions at this time. Of course, you can also change the running user of Nginx to root, but this will compromise security.

//下面是引入的包

import java.nio.file.*;
import java.nio.file.attribute.*;

// 将下面代码放在保存完图片之后
// filePath是 /mnt/image/test.png 这样的绝对路径
                        Path path = Paths.get(filePath);
                        FileOwnerAttributeView fileView = Files.getFileAttributeView(path, FileOwnerAttributeView.class);
                        UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService();
// 保证系统里要有www-data,不然会报错
                        UserPrincipal newOwner = lookupService.lookupPrincipalByName("www-data");
                        fileView.setOwner(newOwner);
// 这里的用户组是root,也可以改成自己想要的用户组
                        GroupPrincipal group = lookupService.lookupPrincipalByGroupName("root");
                        Files.getFileAttributeView(path, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS).setGroup(group);

After the local program saves the picture, execute the above program to give the permissions of the picture to the www-data user, but the user group is root. This can also be changed to the user group you want.

Note: The above procedure must be executed after the image has been saved to the local hard disk.

Guess you like

Origin blog.csdn.net/saperliu/article/details/126617815