java模拟浏览器上传文件
1 public static void main(String[] args) { 2 String str = uploadFile("C:/Users/RGKY/Desktop/wKgBHVbLtuWAVNZAAABB_J2qzhc553.jpg", "http://localhost:8087/worldapp/fastfds/uploadSingleFile.cf?fieldName=selectFile", "wKgBHVbLtuWAVNZAAABB_J2qzhc553.jpg"); 3 System.out.println(str); 4 } 5 6 /** 7 * 8 * @param file 9 * 待上传的文件路径 10 * @param uploadUrl 11 * 上传服务接口路径 12 * @param fileName 13 * 文件名称,服务器获取的文件名称 14 * @return 15 */ 16 public static String uploadFile(/* Bitmap src */String file, String uploadUrl, String fileName) { 17 String end = "\r\n"; 18 String twoHyphens = "--"; 19 String boundary = "******"; 20 try { 21 URL url = new URL(uploadUrl); 22 HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 23 // 设置每次传输的流大小,可以有效防止手机因为内存不足崩溃 24 // 此方法用于在预先不知道内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。 25 httpURLConnection.setChunkedStreamingMode(128 * 1024);// 128K 26 // 允许输入输出流 27 httpURLConnection.setDoInput(true); 28 httpURLConnection.setDoOutput(true); 29 httpURLConnection.setUseCaches(false); 30 // 使用POST方法 31 httpURLConnection.setRequestMethod("POST"); 32 httpURLConnection.setRequestProperty("Connection", "Keep-Alive"); 33 httpURLConnection.setRequestProperty("Charset", "UTF-8"); 34 httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); 35 36 DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream()); 37 dos.writeBytes(twoHyphens + boundary + end); 38 // name相当于html标签file的name属性,fileName相当于标签value值 39 dos.writeBytes("Content-Disposition: form-data;name=\"selectFile\";fileName=\"" + fileName + "\"" + end); 40 dos.writeBytes(end); 41 42 // 将要上传的内容写入流中 43 // InputStream srcis = Function.Bitmap2IS(src); 44 InputStream srcis = new FileInputStream(file); 45 byte[] buffer = new byte[8192]; // 8k 46 int count = 0; 47 // 读取文件 48 while ((count = srcis.read(buffer)) != -1) { 49 dos.write(buffer, 0, count); 50 } 51 srcis.close(); 52 53 dos.writeBytes(end); 54 dos.writeBytes(twoHyphens + boundary + twoHyphens + end); 55 dos.flush(); 56 57 InputStream is = httpURLConnection.getInputStream(); 58 InputStreamReader isr = new InputStreamReader(is, "utf-8"); 59 BufferedReader br = new BufferedReader(isr); 60 // 上传返回值 61 String sl; 62 String result = ""; 63 while ((sl = br.readLine()) != null) 64 result = result + sl; 65 br.close(); 66 is.close(); 67 return result; 68 } catch (Exception e) { 69 e.printStackTrace(); 70 return "网络出错!"; 71 } 72 }