上传文件
分割符前面要加上--,不然没用
要加上网络权限
分析:
1、在android段打开服务器的连接
URL realUrl = new URL("http://192.168.1.100:8080/fileupload/upload");
2、android以post方式请求服务器
conn.setRequestMethod("POST");
3、将手机里面上传的文件信息写入StringBuffer
strBuffer.append("Content-Disposition: form-data; name="file1";filename="bihu.jpg""+ end);
我们上传到服务器里面的是android手机里面的bihu.jpg
4、将android手机里面图片的信息通过输入流和输出流写到服务器上
FileInputStream input = new FileInputStream("/sdcard/bihu.jpg");
其实总结来说:
就是指定输入流位置:android手机上的图片,指定输出流位置:windows上的服务器上的文件夹。
然后就ok了。
1 package com.example.day8_17; 2 3 import java.io.FileInputStream; 4 import java.io.FileNotFoundException; 5 import java.io.IOException; 6 import java.io.OutputStream; 7 import java.net.HttpURLConnection; 8 import java.net.MalformedURLException; 9 import java.net.URL; 10 11 import android.app.Activity; 12 import android.os.AsyncTask; 13 import android.os.Bundle; 14 import android.util.Log; 15 import android.view.View; 16 17 public class MainActivity extends Activity { 18 private String boundary = "*****"; 19 private String end = " "; 20 21 @Override 22 protected void onCreate(Bundle savedInstanceState) { 23 super.onCreate(savedInstanceState); 24 setContentView(R.layout.activity_main); 25 } 26 27 public void onClick(View view) { 28 new AsyncTask<Void, Void, Void>() { 29 @Override 30 protected Void doInBackground(Void... params) { 31 try { 32 uploadFile(); 33 } catch (IOException e) { 34 e.printStackTrace(); 35 } 36 return null; 37 } 38 }.execute(); 39 } 40 41 /** 42 * 上传文件到服务器 43 * 44 * @throws IOException 45 * */ 46 private void uploadFile() throws IOException { 47 URL realUrl = new URL("http://192.168.1.100:8080/fileupload/upload"); 48 HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); 49 // 发送POST请求必须设置允许输出 50 conn.setDoOutput(true); 51 conn.setRequestMethod("POST"); 52 conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" 53 + boundary); 54 // 55 OutputStream output = conn.getOutputStream(); 56 57 StringBuilder strBuffer = new StringBuilder(); 58 strBuffer.append("--"+boundary + end); 59 strBuffer 60 .append("Content-Disposition: form-data; name="file1";filename="bihu.jpg"" 61 + end); 62 strBuffer.append("Content-Type: image/jpeg" + end + end); 63 output.write(strBuffer.toString().getBytes()); 64 // 写出文件 65 writeFile(output); 66 output.write(end.getBytes()); 67 output.write(("--"+boundary).getBytes()); 68 output.close(); 69 // 获取状态码 70 int code = conn.getResponseCode(); 71 if (code == 200) { 72 Log.d("bihu", "上传成功"); 73 } 74 } 75 76 /** 77 * 写出文件 78 * 79 * @throws IOException 80 * */ 81 private void writeFile(OutputStream output) throws IOException { 82 FileInputStream input = new FileInputStream("/sdcard/bihu.jpg"); 83 // 写出数据 84 int len = 0; 85 byte[] buffer = new byte[1024]; 86 while ((len = input.read(buffer)) != -1) { 87 output.write(buffer, 0, len); 88 output.flush(); 89 } 90 } 91 }