栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Vert.x:一个简单的Http文件上传下载的demo

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Vert.x:一个简单的Http文件上传下载的demo

当前版本:jdk1.8、vert.x 4.2.4

1. 声明

当前内容主要为使用Vert.x实现http文件上传和下载,内容参考:官方文档

2. 基本上传下载demo
public class MainVerticle extends AbstractVerticle {
	
	@Override
	public void start(Promise startPromise) throws Exception {
	
		 // Create a Router
	    Router router = Router.router(vertx);
	    
	    // 处理文件上传 
	    router.route("/upload").handler(context->{
	    	HttpServerRequest request = context.request();
	    	request.setExpectMultipart(true);
	    	request.uploadHandler(upload->{
	    		System.out.println("文件上传成功!");
	    		upload.streamToFileSystem("C:\Users\admin\Desktop\upload\" + upload.filename());	
	    	});
	    	context.json(new JsonObject().put("status", 200).put("msg", "upload successed!"));
	    });
	    
	    // 实现文件下载
	    router.route("/download").handler(context->{
	    	HttpServerRequest request = context.request();
	    	System.out.println("文件下载成功!");
	    	request.response()
	    	.putHeader("content-type", "application/octet-stream")
	    	.sendFile("C:\Users\admin\Desktop\nimbus.log");
	    	
	    });
	   

	    // 执行请求操作
	    router.route("/hello").method(HttpMethod.GET).handler(context->{
	    	context.json(new JsonObject("{"status":200,"msg":"ok"}"));
	    });

	    
	 // Create the HTTP server
	    vertx.createHttpServer()
	      // Handle every request using the router
	      .requestHandler(router)
	      // Start listening
	      .listen(8888)
	      // Print the port
	      .onSuccess(server ->
	        System.out.println(
	          "HTTP server started on port " + server.actualPort()
	        )
	      );

	}
}

文件下载:这里直接使用response写出二进制格式(application/octet-stream)文件,如果不写出默认为content-type:text/html格式

这里的文件下载:upload.streamToFileSystem直接将上传的文件存放到特定位置即可(这里默认使用一个存在的文件即可)

关于启动部分参考:基本的Demo

3. 测试

1. 文件下载

2.测试文件上传


文件上传下载测试成功!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/737096.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号