工具类
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
@Slf4j
public class FileUtils {
/*
* @description 获取指定url的文件(非本地)
* @param url 文件路径
* @return file
*/
public static File getfile(String url) throws MalformedURLException {
URL imgurl = new URL(url);
File file = null;
InputStream inStream = null;
OutputStream os =null;
try {
file = File.createTempFile("url", "newfile");
inStream = imgurl.openStream();
os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
}catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (null != os) {
os.close();
}
if (null != inStream) {
inStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return file;
}
下载方法
@RequestMapping(value = "/doDownload", method = {RequestMethod.POST})
@ApiOperation(value = "下载文件",notes = "下载文件",response = RespResult.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "url", value = "文件地址"),
})
public void downloadInstructionsFile( String url, HttpServletResponse response) throws MalformedURLException {
log.info("文件路径:"+url);
InputStream inputStream = null;
OutputStream outputStream = null;
//通过工具获取服务的文件进行实例化
File file = FileUtils.getfile(url);
//设置文件名
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
String formatTime = DateUtil.format(DateUtil.date(), "yyyyMMddHHmm-");
try{
if(file.exists()){
inputStream = new FileInputStream(file);
outputStream = response.getOutputStream();
response.reset();
response.setHeader("Access-Control-Allow-Origin", "http://项目域名");
response.setContentType("application/x-download;charset=GBK");
response.setContentLength((int)file.length());
response.setHeader("Content-Disposition", "attachment;filename="+ new String((formatTime+uuid).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
IOUtils.copy(inputStream,outputStream);
response.getOutputStream().flush();
}else{
log.info("文件不存在");
}
}catch(Exception e){
e.printStackTrace();
}finally {
try{
if(inputStream != null){
inputStream.close();
}
if(outputStream != null){
outputStream.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}