上传到本地webdav-spring boot

q8l4jmvw  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(605)

我上传文件到本地webdav有问题。到目前为止,我已经:

public interface IStorageService {
    URI SaveFile(String filename, InputStream inputStream);
}
@Component
public class LocalStorageService implements IStorageService {
    @Value( "C:\temp" )
    private String filestorePath;

    public URI SaveFile(String filename, InputStream inputStream) {
        var rootLocation = Paths.get(filestorePath);
        var filePath = rootLocation.resolve(filename);
        try {
            Files.copy(inputStream, filePath);
        } catch (IOException e) {
            throw new RuntimeException("Failure save file to " + filename + " in " + filestorePath + "." + e.getMessage(), e);
        }
        return filePath.toUri();
    }
}

和控制器

private final DocumentService documentService;

    public DocumentController(DocumentService documentService) {
        this.documentService = documentService;
    }

    @RequestMapping(method = RequestMethod.POST)
    public DocumentModel handleFileUpload(@RequestParam("file") MultipartFile file) throws IOException {        
        return documentService.handleFileUpload(file.getOriginalFilename(), file.getInputStream());
    }

它工作正常,文件上传到c:/temp。。。现在我想做同样的,但上传文件到本地webdav。当我在@value“c:\temp to”中更改时http://localhost“(这是ma webdav的位置)我有:

invalidpathexception: illegal char <:> at index 4: http://localhost

或者当我声明http//localhost而没有<:>

nosuchfileexception: http\localhost

如何编写代码将文件直接上载到webdav。不能更改savefile方法的参数,我需要使用名称作为string和inputstream。我试过用沙丁鱼,但没用。有人能帮我,给我一些提示或者代码建议吗?
问候语!

vqlkdk9b

vqlkdk9b1#

您可以获得部署web应用程序/war/servlet/控制器的路径:
servletcontext=getcontext();string fullpath=context.getrealpath(“/web inf/test/foo.txt”);
对于spring项目,在controller中

'@Autowired
'ServletContext context;

在控制器方法中:

'String uploadPath = context.getRealPath("") + File.separator + UPLOAD_DIRECTORY;

和真实的文件名,但如果一个用户上传相同的文件两次或两个用户上传相同的文件名呢?
最好把用户id/用户名和日期时间或其他标识符(如txn id)放在子目录中+一些固定文本(如

' String fileName = context.getRealPath("") + File.separator + userId + readlName + "xyz."

extnfrommimetype公司;
并根据您的业务用例将此事务/用户的路径存储在数据库中。
如果mime类型是image/pmg,那么extnfrommimetype将是“png”;如果是jpeg或jpg,则为“jpg”
看见
war/web inf文件夹中资源的文件路径?
如何在SpringMVC控制器中获取getservletcontext()
在springmvc中,使用@responsebody时如何设置mime类型头
https://developer.mozilla.org/en-us/docs/web/http/basics_of_http/mime_types/common_types
如果每个用户/事务可以有多个图像,也可以使用createtemp文件来获取唯一的文件名,也可以使用uuid。。。https://stackoverflow.com/a/1293712/1643558 或者一个大的随机数

相关问题