使用springboot的restTemplate.exchange實現文件下載
目錄結構:
1. application.properties配置文件
demo項目: 下載接口調用方
server.port=8081
server.servlet.context-path=/demo
# http連接超時時間設置
system.http.readTimeout=720
system.http.connectTimeout=720
demo1項目: 下載接口提供方
server.port=8082
server.servlet.context-path=/demo1
2. RestTemplate配置
@Configuration
public class RestTemplateConfig {
/**
* 秒轉換為毫秒的單位
*/
private static final int MILLISECOND_UNIT = 1000;
/**
* http連接的讀取超時時間
*/
@Value("${system.http.readTimeout}")
private int httpReadTimeout;
/**
* http連接的超時時間
*/
@Value("${system.http.connectTimeout}")
private int httpConnectTimeout;
@Bean
public RestTemplate restTemplate() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setReadTimeout(httpReadTimeout * MILLISECOND_UNIT);
requestFactory.setConnectTimeout(httpConnectTimeout * MILLISECOND_UNIT);
return new RestTemplate(requestFactory);
}
}
3. 下載文件
restTemplate.exchange 調用demo2項目的 downloadFile 接口, 結果保存在e盤目錄下
@Service
public class DownloadService {
@Autowired
private RestTemplate restTemplate;
public void downloadFile() {
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(type);
String content = new Gson().toJson("");
HttpEntity<String> entity = new HttpEntity<String>(content, headers);
try {
ResponseEntity<byte[]> bytes = restTemplate.exchange("http://127.0.0.1:8082/demo1/downloadFile", HttpMethod.POST, entity, byte[].class);
String productZipName = "test111.zip";
String path = "E:\\";
File f = new File("E:\\" + productZipName);
if (!f.exists()) {
try {
f.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
try (FileOutputStream out = new FileOutputStream(f);) {
out.write(bytes.getBody(), 0, bytes.getBody().length);
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
UploadUtil.unZip(f, path);
} catch (Exception e) {
e.printStackTrace();
}
}
}
4. 調用工具方法
public class UploadUtil {
public static void unZip(File srcFile, String destDirPath) throws RuntimeException {
long start = System.currentTimeMillis();
// 判斷源文件是否存在
if (!srcFile.exists()) {
throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
}
// 開始解壓
ZipFile zipFile = null;
try {
zipFile = new ZipFile(srcFile, Charset.forName("gbk"));
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
System.out.println("解壓" + entry.getName());
// 如果是文件夾,就創建個文件夾
if (entry.isDirectory()) {
String dirPath = destDirPath + "/" + entry.getName();
File dir = new File(dirPath);
dir.mkdirs();
} else {
// 如果是文件,就先創建一個文件,然后用io流把內容copy過去
File targetFile = new File(destDirPath + "/" + entry.getName());
// 保證這個文件的父文件夾必須要存在
if (!targetFile.getParentFile().exists()) {
targetFile.getParentFile().mkdirs();
}
targetFile.createNewFile();
// 將壓縮文件內容寫入到這個文件中
InputStream is = zipFile.getInputStream(entry);
FileOutputStream fos = new FileOutputStream(targetFile);
int len;
byte[] buf = new byte[1024];
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
// 關流順序,先打開的后關閉
fos.close();
is.close();
}
}
long end = System.currentTimeMillis();
System.out.println("解壓完成,耗時:" + (end - start) + " ms");
} catch (Exception e) {
throw new RuntimeException("unzip error from ZipUtils", e);
} finally {
if (zipFile != null) {
try {
zipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
5. 被調用方, controller
@RestController
public class DownloadController {
@Autowired
private DownloadService downloadService;
@PostMapping("downloadFile")
public void downloadFile(HttpServletRequest request, HttpServletResponse response) {
downloadService.downloadFile(request, response);
}
}
6. 被調用方, service
下載d盤下的 test.zip
@Log
@Service
public class DownloadService {
private static final int ZIP_BUFFER_SIZE = 8192;
public void downloadFile(HttpServletRequest request, HttpServletResponse response) {
try {
String zipFileName = "test.zip";
File file = new File("D:\\test.zip");
if (!file.exists()) {
log.info("下載的軟件包不存在 " + file.getPath());
return;
}
try (InputStream ins = new FileInputStream("D:\\test.zip");
BufferedInputStream bins = new BufferedInputStream(ins);
OutputStream outs = response.getOutputStream();
BufferedOutputStream bouts = new BufferedOutputStream(outs)) {
response.setContentType("application/x-download");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(zipFileName, "UTF-8"));
int bytesRead = 0;
byte[] buffer = new byte[ZIP_BUFFER_SIZE];
while ((bytesRead = bins.read(buffer, 0, ZIP_BUFFER_SIZE)) != -1) {
bouts.write(buffer, 0, bytesRead);
}
bouts.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}