1. import org.slf4j.Logger;
    2. import org.slf4j.LoggerFactory;
    3. import java.io.DataInputStream;
    4. import java.io.DataOutputStream;
    5. import java.io.FileOutputStream;
    6. import java.io.IOException;
    7. import java.net.HttpURLConnection;
    8. import java.net.URL;
    9. import java.util.Objects;
    10. /**
    11. * 下载网络远程图片
    12. *
    13. * @author saber
    14. */
    15. public class DownImgUtils {
    16. private static Logger LOGGER = LoggerFactory.getLogger(DownImgUtils.class);
    17. public static String downloadURL(String fileUrl) {
    18. //LOGGER.info("开始执行将图片下载到本地,fileUrl:{}",fileUrl);
    19. String fileName = "";
    20. //获取文件名,文件名实际上在URL中可以找到
    21. int pos = fileUrl.indexOf('?');
    22. String newUrl = fileUrl;
    23. if (pos > 0) {
    24. newUrl = newUrl.substring(0, pos);
    25. }
    26. pos = newUrl.lastIndexOf('/');
    27. fileName = newUrl.substring(pos + 1);
    28. fileName = "uploadImg_" + fileName;
    29. //这里服务器上要将此图保存的路径
    30. String savePath = System.getProperty("java.io.tmpdir");
    31. fileName = savePath +"/"+ fileName;
    32. HttpURLConnection connection = null;
    33. DataInputStream in = null;
    34. DataOutputStream out = null;
    35. try {
    36. URL url = new URL(fileUrl);
    37. connection = (HttpURLConnection) url.openConnection();
    38. connection.setReadTimeout(30000);
    39. connection.setConnectTimeout(30000);
    40. in = new DataInputStream(connection.getInputStream());
    41. out = new DataOutputStream(new FileOutputStream(fileName));
    42. byte[] buffer = new byte[4096];
    43. int count = 0;
    44. while ((count = in.read(buffer)) > 0) {
    45. out.write(buffer, 0, count);
    46. }
    47. out.close();
    48. in.close();
    49. connection.disconnect();
    50. } catch (Exception e) {
    51. System.out.println(e + fileUrl + savePath);
    52. } finally {
    53. try {
    54. if (Objects.nonNull(out)) {
    55. out.close();
    56. }
    57. } catch (IOException e) {
    58. e.printStackTrace();
    59. }
    60. try {
    61. if (Objects.nonNull(in)) {
    62. in.close();
    63. }
    64. } catch (IOException e) {
    65. e.printStackTrace();
    66. }
    67. connection.disconnect();
    68. }
    69. //LOGGER.info("结束执行将图片下载到本地,fileUrl:{}",fileUrl);
    70. return fileName;
    71. }
    72. }