java 工具 | 在两台电脑之间传文字和文件

本贴最后更新于 1501 天前,其中的信息可能已经水流花落

工具体验

网址: http://tools.lixiang.red/tools/sync/textPage

ch2DY0

制作思路

这个是从 teamview 中想到的。用 TeamView 远程的时候来定位两台电脑,所以我这里也用了 id-value 的形式。

文字使用 HashMap<id+value,content> 来存储,内容在获取之后就会删掉,没有持久化

文件使用 HashMap<id+value,Path> 来存储,然后文件在获取之后就会被删掉,没有做持久化。

工具源码

前端

技术点:

  1. thymeleaf
  2. AJAX

前端 HTML 的代码:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>同步工具</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <link href="/css/bootstrap.min.css" th:href="@{https://cdn.bootcss.com/twitter-bootstrap/4.3.1/css/bootstrap.min.css}" rel="stylesheet">
</head>
<body class="container">
id: <input th:id="currentId" th:value=" ${id}" />
value: <input th:id="currentPassword" th:value=" ${password}" />
<div class="row">
    <div class="col-7">
        <input onclick="syncText(0)" type="button" th:value="获取">
        <input onclick="syncText(1)" type="button" th:value="上传">
        <div>
            <textarea th:id="currentContent" th:rows="30" style="width: 100%"></textarea>
        </div>
    </div>

    <div class="col-3">
        同步文件: 只能10M以下
        <input th:id="file_input" type="file">
        <input type="button" onclick="syncFile(1)" value="上传">
        <input type="button" onclick="syncFile(0)" value="下载">
    </div>
</div>


<div>
    <div>微信扫一扫,更多技术好文:</div>

    <img src="/img/java_subscribe.jpg">
</div>

<script type="text/javascript">
    function syncText(opt) {
        var id  = $("#currentId").val();
        var  password = $("#currentPassword").val();
        var content = $("#currentContent").val();
        var request={content:content,id:id,password:password}
        if(opt ===1){
            $.ajax({
                url:'/tools/sync/text',
                type:'post',
                contentType:'application/json',
                data:JSON.stringify(request),
                success:function (data) {

                }
            })
        }
        if(opt===0){
            $.ajax({
                url:'/tools/sync/text',
                type:'post',
                contentType:'application/json',
                data:JSON.stringify({id:id,password:password}),
                success:function (data) {
                    $('#currentContent').val(data);
                }
            })
        }
    
    }
    function syncFile(opt) {
        var id  = $("#currentId").val();
        var password = $("#currentPassword").val();
        var formD = new FormData();
        formD.append("file",$("#file_input")[0].files[0]);
    
        if(opt === 1){
            $.ajax({
                url:'/tools/sync/file?id='+id+'&password='+password,
                type:'post',
                contentType:false,
                processData: false,
                data:formD,
                success:function (data) {
                    alert(data)
                }
            })
        }
        if(opt ===0){
            window.location.href = "/tools/sync/getFile?id="+id+"&password="+password;
        }


    }
</script>
</body>
</html>

后端

技术点:

  1. webflux 的使用
  2. Path,Files 的使用

后端 Java 代码:

@Controller
public class SyncContentController {
		
  	// 存放文字的
    private Map<String, String> cache = new HashMap<>();
		// 存放文件的
    private Map<String, String> fileCache = new HashMap<>();

    @RequestMapping("tools/sync/text")
    @ResponseBody
    public String syncText(@RequestBody SyncContentRequest request) {
        String key = request.getId() + "-" + request.getPassword();
        String result = "";
        if (StringUtils.isBlank(request.getContent())) {
            result = cache.get(key);
            cache.remove(key);
        } else {
            cache.put(key, request.getContent());
        }
        return result;
    }
    
    @RequestMapping("tools/sync/textPage")
    public String syncTextPage(Model model) {
    			// 返回页面的时候,同时生成默认的id 和 value
        String currentId = RandomTools.getComCharStr(6);
        String password = RandomTools.getComCharStr(6);
        model.addAttribute("id", currentId);
        model.addAttribute("password", password);
    
        return "test";
    }
    
    @RequestMapping("tools/sync/file")
    @ResponseBody
    public String syncFile(@RequestPart(value = "file") FilePart file, @RequestParam("id") String id,@RequestParam("password") String password) {
        try {
          // 上传文件,因为使用的是webflux ,  所以不太一样
            String key = id + password;
            String filePath = key + "/" + file.filename();
            Files.createDirectories(Paths.get(key));
            Path tempFile = Files.createFile(Paths.get(filePath));
            file.transferTo(tempFile.toFile());
            fileCache.put(key, filePath);
            return "OK";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "fail";
    }
    
    @RequestMapping("tools/sync/getFile")
    public ResponseEntity getFile(String id, String password) throws IOException {
    			// 获取文件的, 使用的是webflux
        String key = id + password;
        String filePath = fileCache.get(key);
        String suffix = FileTools.getSuffixName(filePath);
        byte[] bytes = Files.readAllBytes(Paths.get(filePath));
      	// 读取完就删除文件
        Files.deleteIfExists(Paths.get(filePath));
        Files.deleteIfExists(Paths.get(key));
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        String s = URLEncoder.encode("公众号-白天想懂夜的黑", "UtF-8");
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+s+"." + suffix)
                .body(new InputStreamResource(inputStream));
    }

总结

今天总结推荐一个公众号: 白天想懂夜的黑。 疫情当下,如果你觉得很闷得慌,可以来说一说,或者有什么想倾诉的 ,想什么问题,都可以来说一说,公众号内直接留言就可。

loveyou

  • 工具

    子曰:“工欲善其事,必先利其器。”

    273 引用 • 676 回帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...