자바 URL 로 이미지 다운로드 - 간단 한 구현

2007 단어 JAVA 기초
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;


@Api(tags = "    ")
@RestController
@RequestMapping("/v1/bestore/services")
@Validated
public class TestDownLoadRest {

    @RequestMapping(value = {"/download"}, produces = "application/json", method = RequestMethod.GET)
    @ApiOperation(value = "    ,urlList   URL  ,path          D://")
    public void download(@RequestParam("urlList") String urlList,@RequestParam("path") String path) {
        URL url = null;
        try {
            url = new URL(urlList);
            //     
            URLConnection con = url.openConnection();
            //       5s
            con.setConnectTimeout(5*1000);
            //    
            InputStream is = con.getInputStream();
            // 1K     
            byte[] bs = new byte[1024];
            //         
            int len;
            //       
            File sf=new File(path);
            if(!sf.exists()){
                sf.mkdirs();
            }
            //        ,    
            OutputStream os = new FileOutputStream(sf.getPath()+"\\"+System.currentTimeMillis()+".png");
            //     
            while ((len = is.read(bs)) != -1) {
                //    
                os.write(bs, 0, len);
            }
            //   ,      
            os.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

좋은 웹페이지 즐겨찾기