2016-03-21 59 views
0

有沒有什麼辦法可以使用spring web,security-oauth stack來生成下載文件的臨時鏈接?春天生成下載鏈接

例如domain.com/document/ed3dk4kfjw34k43kd4k3cc僅適用於當前會話?

回答

1

您可以嘗試將Map<String, String>添加到會話中。之後,您可以將生成的唯一字符串和文件名存儲到此映射中。每當需要通過唯一生成的字符串加載文件時,您將通過字符串找到真實的文件名並將其發送給客戶端。用於演示思想的簡單組件:

@Component 
@Scope(value = "session") 
public class SessionFileMap { 

    private Map<String, String> fileMap = new HashMap<>(); 

    public String getUniqueString(String fileName){ 
     for(String uniqueName: fileMap.keySet()){ 
      //check, if file already in map, return it 
      if(fileMap.get(uniqueName).equals(fileName)) return uniqueName; 
     }    
     //otherwise, create new 
     String uniqueName = generateUniqueName(); 
     fileMap.put(uniqueName, fileName); 
     return uniqueName; 
    } 

    public String getFileName(String uniqueString){ 
     if(fileMap.containsKey(uniqueString)){ 
      return fileMap.get(uniqueString); 
     } 
     return null; 
    } 

    private String generateUniqueName() { 
     String uniqueString = //generation of unique string 
     return uniqueString; 
    } 
} 

當然,您必須使該組件的作用域爲session。和there is很好的例子,你如何生成獨特的字符串。現在例如該組分的用法:

@Controller 
@Scope(value = "session") 
public class FileController { 

    @Autowired 
    private SessionFileMap fileMap; 

    @Autowired 
    private ApplicationContext context; 

    @RequestMapping("/file") 
    public String showLink(ModelMap model, HttpSession session){ 
     String uniqueString = fileMap.getUniqueString("/filepath/filename.ext"); 
     model.addAttribute("uniqueString", uniqueString); 
     return "file"; 
    } 

    @RequestMapping("/download/{uniqueString}") 
    public void download(@PathVariable("uniqueString") String uniqueString, 
          HttpServletResponse response){ 
     String fileName = fileMap.getFileName(uniqueString); 
     try{ 
      Resource resource = context.getResource("file:"+fileName); 
      try (InputStream is = resource.getInputStream()) { 

       //prepare all headers for download ... 

       IOUtils.copy(is, response.getOutputStream()); 
       response.flushBuffer(); 
      } 
     }catch(Exception e){ 
      throw new RuntimeException(e); 
     } 
    } 
} 

控制器必須具有的session範圍以及組件。如果你注意到,我用IOUtils.copy()org.apache.commons複製流,但你可以按你的意願去做。鑑於此,鏈接如下所示:

<html> 
<head> 
    <title></title> 
</head> 
<body> 
    <a href="/download/${uniqueString}">Download</a> 
</body> 
</html> 

這只是對基本思想的演示。所有的細節都取決於你。

+0

所以框架不提供任何現成的解決方案? – Fr0stDev1

+1

@ Fr0stDev1似乎是如此。至少在Spring Framework中我沒有看到「準備好使用」的解決方案。 –