最近在使用Nginx代理直接读取硬盘图片的时候,发现Nginx无权读取文件,是因为文件的拥有者是root,而Nginx的运行用户是www-data,所以无法访问到图片。而程序在存储图片时默认的都是root,所以这时候需要设置文件的权限,当然也可以把Nginx的运行用户改为root,但这样安全性会打折扣。
//下面是引入的包
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);
在本地程序保存完图片后,执行上面的程序即可以将图片的权限给予 www-data用户,但用户组是root,这个也可以改成自己想要的用户组。
注意:上面程序一定要在图片已经保存到本地硬盘以后再执行。