包含两种处理
1、填到response返回
2、保存到指定路径
1、填到response返回
// 访问远程地址获取文件,并将文件填充到请求输出流中
public String getQrCodeStream(HttpServletResponse response) {
// 文件地址,浏览器访问文件地址可以直接下载文件
String qrCodeUrl = "这是一个远程地址,如: https://mass.alipay.com/wsdk/img.png";
URL url = null;
byte[] buffer = new byte[1024];
try {
url = new URL(qrCodeUrl);
InputStream is = url.openStream();
OutputStream output = response.getOutputStream();
for (int length = 0; (length = is.read(buffer)) > 0; ) {
output.write(buffer, 0, length);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
2、保存到指定路径
public class SaveFileTest {
public static void main(String[] args) throws IOException {
// 读取文件
String qrCodeUrl = "https://mass.alipay.com/wsdk/img.png";
URL url = new URL(qrCodeUrl);
InputStream inputStream = url.openStream();
String targetPath = "F://test.png";
OutputStream os = null;
os = new FileOutputStream(targetPath);
// 开始读取
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流保存到本地文件
while ((len = inputStream.read(bs)) != -1) {
os.write(bs, 0, len);
}
}
}