分别使用Http方式和HttpClient方式向服务器上传图片
服务器端
建立UploadServlet.java 文件,接收上传的文件数据,指定在服务器端存储的位置。
/**
*
* @author meng.li
* 指定文件的存储位置为E盘
*/
@MultipartConfig(
location ="E:\\"
)
public class UploadServlet extends HttpServlet {
public UploadServlet() {
super();
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Part par = request.getPart("file");
par.write("test.jpg");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.print("upload success!");
}
public void init() throws ServletException {
}
}
客户端
文件上传线程 UploadThread.java
public class UploadThread extends Thread{
private String fileName;
private String url;
public UploadThread(String fileName,String url){
this.fileName = fileName;
this.url = url;
}
@Override
public void run() {
uploadHttpClient();
// httpUpload();
}
private void uploadHttpClient(){
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
File parent = Environment.getExternalStorageDirectory();
File filAbs = new File(parent,"image.jpg");
MultipartEntity muti = new MultipartEntity();
FileBody fileBody = new FileBody(filAbs);
muti.addPart("file",fileBody);
post.setEntity(muti);
try {
HttpResponse response = client.execute(post);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
Log.i("meng",EntityUtils.toString(response.getEntity())+"");
}
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
//使用http方式上传图片,需要进行拼接,比较麻烦
private void httpUpload(){
String boundary = "----WebKitFormBoundaryP0Rfzlf32iRoMhmb";
//实际用到的时候会多两个杠杠 ------WebKitFormBoundaryP0Rfzlf32iRoMhmb
String prefix = "--";
String end = "\r\n";
try {
URL httpUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
//通过multipart这种编码方式上传文件
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
//拼装要上传的文件
out.writeBytes(prefix+boundary+end);
out.writeBytes("Content-Disposition: form-data;"
+"name=\"file\";filename=\""+"Sky.jpg" +"\""+end);
out.writeBytes(end);
FileInputStream inputStream = new FileInputStream(new File(fileName));
byte[] b = new byte[1024*4];
int len;
while((len = inputStream.read(b))!= -1){
out.write(b,0,len);
}
out.writeBytes(end);
out.writeBytes(prefix+boundary+prefix+end);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String str = null;
StringBuffer sb = new StringBuffer();
while((str = bufferedReader.readLine())!= null){
sb.append(str);
}
if(out != null){
out.close();
}
if(inputStream != null){
inputStream.close();
}
if(bufferedReader != null){
bufferedReader.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
上面需要用到HttpClient的两个jar包 httpmime-4.0.1.jar 和 apache-mime4j-0.6.jar
jar包版本会导致很多错误 提供Jar包的下载地址为:
http://download.csdn.net/detail/u010583599/9581257
调用类 MainActivity.java
调用类 MainActivity.java
public class MainActivity extends Activity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.upload);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String url = "http://192.168.199.126:8080/Server/UploadServlet";
File file = Environment.getExternalStorageDirectory();
File fileAbs = new File(file,"image.jpg");
String fileName = fileAbs.getAbsolutePath();
UploadThread thread = new UploadThread(fileName, url);
thread.start();
}
});
}
}