android上傳圖片然後在加載出來顯示。
網上看了看,大部分用的是以流的方式post過去。
首先android端:(只貼出關鍵性代碼)
以下是裝載ImageView顯示圖片並且得到裝載後的圖片的路徑picPath
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == TO_SELECT_PHOTO) {
picPath = data.getStringExtra(SelectPicActivity.KEY_PHOTO_PATH);
File file = new File(picPath);
if (file != null && file.exists()) {
Options opts = new Options();
opts.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), opts);
btn_add_camera.setImageBitmap(bitmap);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
以下是返回的結果
case R.id.btn_add_camera://相機按鈕
Intent intent = new Intent(AddCataLogActivity.this, SelectPicActivity.class);
startActivityForResult(intent, TO_SELECT_PHOTO);
break;
有以上兩步之後就可以上傳了
if(!picPath.equals("")){//post上傳
String actionUrl = "http://192.168.1.155:8886/FruitProject/GreenServlet";
UpLoadImg.uploadImg(actionUrl, picPath);
}
以上的uploadImg會打包
最後一步就是servlet端接受了
//post傳照片
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
//先上傳圖片 之後再添加到數據庫
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHms");
String cp11111 = request.getSession().getServletContext().getRealPath("/") + "Img/";
ImgName = format.format(new Date()) + ".jpg";// 時間的格式(圖片字段)
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> list = upload.parseRequest(request);
System.out.println(list + " list " + list.size());
for (FileItem item : list) {
if (item.isFormField() == false) {
File f = new File(cp11111 + ImgName);
item.write(f);
System.out.println("write filt success");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
如此的簡單。。。。。
顯示出來就更簡單了,一句代碼。
mApplication.mGalleryBitmap.display(holder.myimg, "http://192.168.1.155:8886/FruitProject/Img/" + Listcatalog.getImgpath());