伺服器端代碼:
package servie;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class UpLoadImage
*/
public class UpLoadImage extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UpLoadImage() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
// User user=(User)session.getAttribute("user");
// long id=user.getId();
//String path=request.getSession().getServletContext().getRealPath("/");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory);
try {
List<FileItem> items = sfu.parseRequest(request);
for(int i =0;i<items.size();i++){
FileItem item =items.get(i);
if(item.isFormField()){
String name = item.getString();
System.out.println("name"+name);
}
else{
ServletContext context = getServletContext();
String path =context.getRealPath("/pic");
//File file = new File(path+"/pic");
//file.mkdir();
String fileName1 = item.getName();
String fileName = fileName1.substring(fileName1.lastIndexOf("/")+1);
File file = new File(path+"/"+fileName);
item.write(file);
System.out.println("成功!");
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
android用戶端代碼
package com.example.imageupload;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
@SuppressLint("NewApi")
public class MainActivity extends Activity {
private String newName ="image.jpg";
private String uploadFile ="/sdcard/EditPlus.jpg";
private String actionUrl ="http://172.16.77.58:8080/WebImageUpload/UpLoadImageTest";
private TextView mText1;
private TextView mText2;
private Button mButton;
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
setContentView(R.layout.main);
mText1 = (TextView) findViewById(R.id.myText2);
//"檔案路徑:
"+
mText1.setText(uploadFile);
mText2 = (TextView) findViewById(R.id.myText3);
//"上傳網址:
"+
mText2.setText(actionUrl);
/* 設定mButton的onClick事件處理 */
mButton = (Button) findViewById(R.id.myButton);
mButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
uploadFile();
}
});
}
/* 上傳檔案至Server的方法 */
private void uploadFile()
{
String end ="
";
String twoHyphens ="--";
String boundary ="*****";
try
{
URL url =new URL(actionUrl);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
/* 允許Input、Output,不使用Cache */
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
/* 設定傳送的method=POST */
con.setRequestMethod("POST");
/* setRequestProperty */
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type",
"multipart/form-data;boundary="+boundary);
/* 設定DataOutputStream */
DataOutputStream ds = new DataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; "+
"name="file1";filename=""+
newName +"""+ end);
ds.writeBytes(end);
/* 取得檔案的FileInputStream */
FileInputStream fStream =new FileInputStream(uploadFile);
/* 設定每次寫入1024bytes */
int bufferSize =1024;
byte[] buffer =new byte[bufferSize];
int length =-1;
/* 從檔案讀取資料至緩沖區 */
while((length = fStream.read(buffer)) !=-1)
{
/* 将資料寫入DataOutputStream中 */
ds.write(buffer, 0, length);
}
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
/* close streams */
fStream.close();
ds.flush();
/* 取得Response内容 */
InputStream is = con.getInputStream();
int ch;
StringBuffer b =new StringBuffer();
while( ( ch = is.read() ) !=-1 )
{
b.append( (char)ch );
}
/* 将Response顯示于Dialog */
showDialog("上傳成功"+b.toString().trim());
/* 關閉DataOutputStream */
ds.close();
}
catch(Exception e)
{
showDialog("上傳失敗"+e);
}
}
/* 顯示Dialog的method */
private void showDialog(String mess)
{
new AlertDialog.Builder(MainActivity.this).setTitle("Message")
.setMessage(mess)
.setNegativeButton("确定",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
}
})
.show();
}
}
轉自:http://www.cnblogs.com/gzggyy/archive/2011/08/02/2125237.html