• java HttpURLConnection 接口文件传输文件上传


     1 public   String uploadImg(MultipartFile imgFile, String uploadUrl) throws  Exception {
     2 
     3         URL url = new URL(uploadUrl);
     4         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
     5         conn.setConnectTimeout(10000);
     6         conn.setRequestMethod("POST");
     7         conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=----123456789");
     8         conn.setDoInput(true);
     9         conn.setDoOutput(true);
    10 
    11         OutputStream os = new DataOutputStream(conn.getOutputStream());
    12         StringBuilder body = new StringBuilder();
    13         body.append("------123456789
    ");
    14         body.append("Content-Disposition: form-data; name='images'; filename='" + imgFile.getName() + "'
    ");
    15 
    16         //没有传入文件类型,同时根据文件获取不到类型,默认采用application/octet-stream
    17       String   contentType ="";
    18       String filename=imgFile.getName();
    19         //contentType非空采用filename匹配默认的图片类型
    20         if (filename.endsWith(".png")) {
    21             contentType = "image/png";
    22         }else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
    23             contentType = "image/jpeg";
    24         }else if (filename.endsWith(".gif")) {
    25             contentType = "image/gif";
    26         }else if (filename.endsWith(".ico")) {
    27             contentType = "image/image/x-icon";
    28         }
    29 
    30         if (contentType == null || "".equals(contentType)) {
    31             contentType = "application/octet-stream";
    32         }
    33 
    34         body.append("Content-Type: "+contentType+"
    
    ");
    35         os.write(body.toString().getBytes());
    36 
    37             InputStream is =  imgFile.getInputStream();
    38             byte[] b = new byte[1024];
    39             int len = 0;
    40             while ((len = is.read(b)) != -1) {
    41                 os.write(b, 0, len);
    42             }
    43             String end = "
    ------123456789--";
    44             os.write(end.getBytes());
    45 
    46             //输出返回结果
    47         BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    48         StringBuilder stringBuilder = new StringBuilder();
    49         String line = "";
    50         for (line = br.readLine(); line != null; line = br.readLine()) {
    51 
    52             stringBuilder.append(line);
    53         }
    54         return stringBuilder.toString();
    55 
    56    }
    -- 沉着,冷静,bug总会解决,未来道路很光明。
  • 相关阅读:
    小试牛刀,建立jsp网页与导出war包
    IDEA 官方背景与修改jsp模板以及字体大小
    类库日期和jsp导包
    eclipse配置
    mysql绿色版下载及应用
    创建一个学生信息表,与页面分离
    Tomcat配置
    c#简单加密和对称加密
    04面向对象基础
    ADO.NET复习——自己编写SqlHelper类
  • 原文地址:https://www.cnblogs.com/dadadajiong/p/12837530.html
Copyright © 2020-2023  润新知