gpt4 book ai didi

java - 基于用户组的可变文件存储路径

转载 作者:行者123 更新时间:2023-12-01 16:30:45 25 4
gpt4 key购买 nike

我正在开发一个允许用户上传文件的应用程序。我想将上传的文件组织到以用户所属组命名的预先创建的文件夹中。我似乎找不到一种方法使路径可编辑,以便我可以将组的名称作为参数传递到方法中并将文件存储在该目录中。

这是我最近的尝试,导致“无法存储文件文件],根本原因”异常。

@Service
public class StorageServiceImpl implements StorageService {

@Value("${upload.path}")
private Path path;

public void uploadFile(MultipartFile file,String contentName, String groupName){
//make so that files are stored in path/groupname
this.path = Paths.get(this.path.toString() +"/"+groupName +"/");
String filename = contentName+"-"+StringUtils.cleanPath(file.getOriginalFilename());
System.out.println("\n\n\n\n\n"+filename + "\n\n\n");
try {
if (file.isEmpty()) {
throw new StorageException("Failed to store empty file");
}
if (filename.contains("..")) {
// This is a security check
throw new StorageException(
"Cannot store file with relative path outside current directory "
+ filename);
}
try (InputStream inputStream = file.getInputStream()) {
System.out.println("\n\n\n\n\n"+this.path.resolve(filename) + "\n\n\n");
Files.copy(inputStream, this.path.resolve(filename), StandardCopyOption.REPLACE_EXISTING);
}
}catch (IOException e) {
String msg = String.format("Failed to store file %s", file.getName());
throw new StorageException(msg, e);
}
}
}

注意:如果在此方法运行之前创建了 groupName 的目录(因为我打算在创建组时创建它),则该方法会尝试将文件存储在该目录内的另一个同名目录中,例如如:

后端/src/main/webapp/WEB-INF/TestGroup/TestGroup/test.jpg

看看 TestGroup 如何出现两次

最佳答案

这里您尝试将值注入(inject) Path 类型的变量,而不是这样做。

@Value("${upload.path}")
private Path path;

如何将值读取到字符串变量并将其存储为文件,然后使用它来上传,如下所示,

@Value("${upload.path}")
private String path;

然后使用它

public void uploadFile( MultipartFile file, String contentName, String groupName )
{
String filename = contentName + "-" + StringUtils.cleanPath( file.getOriginalFilename() );
// use a File object here
File uploadFilePath = Paths.get( new File( path ).getPath() + "/" + groupName + "/" + filename ).toFile();
try
{
try( InputStream in = file.getInputStream(); OutputStream out = new FileOutputStream( uploadFilePath ) )
{
// Leverage the support of Spring's FileCopyUtils Here
FileCopyUtils.copy( in, out );
}
catch( IOException ex )
{
throw new RuntimeException( ex );
}
}
catch( IOException e )
{
String msg = String.format( "Failed to store file %s", file.getName() );
throw new StorageException( msg, e );
}
}

关于java - 基于用户组的可变文件存储路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62047400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com