android上傳圖片至服務器
本實例實現了android上傳手機圖片至服務器,服務器進行保存服務器servlet代碼
publicvoid doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String temp=request.getSession().getServletContext().getRealPath("/")+"temp"; //臨時目錄
System.out.println("temp="+temp);
String loadpath=request.getSession().getServletContext().getRealPath("/")+"Image"; //上傳文件存放目錄
System.out.println("loadpath="+loadpath);
DiskFileUpload fu =new DiskFileUpload();
fu.setSizeMax(1*1024*1024); // 設置允許用戶上傳文件大小,單位:字節
fu.setSizeThreshold(4096); // 設置最多只允許在內存中存儲的數據,單位:字節
fu.setRepositoryPath(temp); // 設置一旦文件大小超過getSizeThreshold()的值時數據存放在硬盤的目錄
//開始讀取上傳信息
int index=0; List fileItems =null;
try {
fileItems = fu.parseRequest(request);
System.out.println("fileItems="+fileItems);
} catch (Exception e) {
e.printStackTrace();
}
Iterator iter = fileItems.iterator(); // 依次處理每個上傳的文件
while (iter.hasNext()) { FileItem item = (FileItem)iter.next();// 忽略其他不是文件域的所有表單信息 if (!item.isFormField()) { String name = item.getName();//獲取上傳文件名,包括路徑 name=name.substring(name.lastIndexOf("\")+1);//從全路徑中提取文件名 long size = item.getSize(); if((name==null||name.equals("")) && size==0) continue; int point = name.indexOf("."); name=(new Date()).getTime()+name.substring(point,name.length())+index; index++; File fNew=new File(loadpath, name); try { item.write(fNew); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }
}
else//取出不是文件域的所有表單信息
{
String fieldvalue = item.getString();
//如果包含中文應寫為:(轉為UTF-8編碼)
//String fieldvalue = new String(item.getString().getBytes(),"UTF-8");
}
}
String text1="11";
response.sendRedirect("result.jsp?text1="+ text1);
} </pre></span> <span style="border-collapse:collapse;font-family:Arial;color:#333333;" class="Apple-style-span">android客戶端代碼<pre class="brush:java; toolbar: true; auto-links: false;">public class PhotoUpload extends Activity {
private String newName ="image.jpg";
private String uploadFile ="/sdcard/image.JPG";
private String actionUrl ="http://192.168.0.71:8086/HelloWord/myForm";
private TextView mText1;
private TextView mText2;
private Button mButton;
@Override
publicvoid onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.photo_upload);
mText1 = (TextView) findViewById(R.id.myText2);
//"文件路徑:\n"+
mText1.setText(uploadFile);
mText2 = (TextView) findViewById(R.id.myText3);
//"上傳網址:\n"+
mText2.setText(actionUrl);
/* 設置mButton的onClick事件處理 */
mButton = (Button) findViewById(R.id.myButton);
mButton.setOnClickListener(new View.OnClickListener()
{
publicvoid onClick(View v)
{
uploadFile();
}
});
}
/* 上傳文件至Server的方法 */
privatevoid uploadFile()
{
String end ="\r\n";
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 =newbyte[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 */
privatevoid showDialog(String mess)
{
new AlertDialog.Builder(PhotoUpload.this).setTitle("Message")
.setMessage(mess)
.setNegativeButton("確定",new DialogInterface.OnClickListener()
{
publicvoid onClick(DialogInterface dialog, int which)
{
}
})
.show();
}
}</pre></span>