文件下载功能的前后端实现(RestSharp + SpringBoot)

本周某项目中要实现一个文件下载功能,服务器端和电脑端都要开发。

服务器端:SpringBoot实现, 电脑端RestSharp实现,经过一番探索之后搞定,代码如下:

SpringBoot:

@GetMapping("/download-client")
public ResponseEntity<Resource> downloadClient() throws IOException {
	String filePath = "C:\\test.txt";
	File file = new File(filePath);
	InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

	return ResponseEntity.ok()
	            .contentLength(file.length())
	            .contentType(MediaType.APPLICATION_OCTET_STREAM)
	            .body(resource);
}

RestSharp:

var client = new RestClient(url);
var request = new RestRequest(Method.GET);
request.AddHeader("Cache-Control", "no-cache");
IRestResponse response = client.Execute(request);

string destPath = "C:\test.txt"
byte[] bytes = client.DownloadData(request);
File.WriteAllBytes(destPath, bytes);

不得不感叹IT行业生产力提高的速度。想起2012年刚入行的时候,下载文件也是挺麻烦的功能,没这么多现成的方案可用。随着编程语言与工具的繁荣,如今已经是小菜一碟了。

猜你喜欢

转载自blog.csdn.net/zhouyingge1104/article/details/115141028
今日推荐