目录
1.工具类
public class UrlToFileUtil {
public static void urlToFile(String path,HttpServletResponse response){
ServletOutputStream outputStream = null;
InputStream inputStream = null;
try {
URL url = new URL(path);
URLConnection connection = url.openConnection();
inputStream = connection.getInputStream();
byte[] buffer = new byte[1024];
outputStream = response.getOutputStream();
int bytesRead;
while ((bytesRead=inputStream.read(buffer))!=-1){
outputStream.write(buffer,0,bytesRead);
}
}catch (Exception e){
throw new ErrorMsgException("文件下载失败");
}finally {
if (!Objects.isNull(inputStream)){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (!Objects.isNull(outputStream)){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.接口
@ApiOperation(value = "地址转文件", notes = "地址转文件", httpMethod = "POST")
@RequestMapping(value = "/urlToFile", method = RequestMethod.POST)
public void uploadImage(String path,HttpServletResponse response) {
UrlToFileUtil.urlToFile(path,response);
}