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\r\n");
14         body.append("Content-Disposition: form-data; name='images'; filename='" + imgFile.getName() + "'\r\n");
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+"\r\n\r\n");
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 = "\r\n------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    }