`
最美的挨踢梦想
  • 浏览: 6942 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

android中实现将图片上传到服务器的问题

阅读更多
这是自己在练习做一个将图片上传到服务器端android应用时遇到的一些问题及一些常用的android代码的一些分享:

我设计了两种方法,一种是通过照相机拍照上传一种是上传本地照片的方式,但是其核心的内容都是一致的!下面我就以上传本地图片来进行说明:
1、首先是要从图库中选择图片,这个代码的格式比较固定:
      Intent intent=new Intent();
     intent.setType(IMAGE_TYPE); intent.setAction(Intent.ACTION_GET_CONTENT);//打开图像库
startActivityForResult(intent, 1);
2、接下来就是选择图片时得到选择图片的路径:

           uri=data.getData();//获得图片的uri
        try { //bm=MediaStore.Images.Media.getBitmap(cr, uri);
String[] proj={MediaStore.Images.Media.DATA};
//Cursor 是android.database包下的
Cursor cursor=managedQuery(uri, proj, null, null, null);
int column_index=cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();    //小心游标越界,要将其移动到前段
           path=cursor.getString(column_index);
}
3、接下来就是服务器端和客户端的设计了,首先是服务器端的设计:

   我这里就列出核心的代码

    //这是一个servlet中的service方法
    protected void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
   // System.out.println("out");
     request.setCharacterEncoding("utf-8");
    String imagePath=request.getSession().getServletContext().getRealPath("/")+"image";//存放上传照片的路径
     //System.out.println("image---"+imagePath);
     File dir=new File(imagePath);
     if(!dir.exists()){
       dir.mkdirs();
     }
    DiskFileItemFactory dfi=new DiskFileItemFactory();//是commons包下的
    ServletFileUpload sfu=new ServletFileUpload(dfi);
     sfu.setSizeMax(100*1024*1024);     //设置最大可以上传的文件大小为100M
     try {
   List <FileItem>items=sfu.parseRequest(request);
for(int i=0;i<items.size();i++){
  FileItem item=items.get(i);
  String imageName="";
            if(!item.isFormField()){
     String fileName=item.getName(); imageName=fileName.substring(fileName.lastIndexOf("/")+1);

long size=item.getSize();
if((imageName==null||imageName.equals(""))&&size==0){ continue;
}
int point =imageName.indexOf(".");
         imageName=(new Date()).getTime()+imageName.
substring(point,imageName.length());
File imageUpload=new File(imagePath,imageName);
item.write(imageUpload);
}else{//取出不是文件域的所有表单信息
String fieldValue=item.getString();
   //如果包含中文应写为
   //String fieldValue=new String(item.getString().getBytes(),"utf-8");
}
System.out.println("imageName"+imageName);
response.sendRedirect("index.jsp?file="+imageName);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
    }
}
上面的代码显得有些乱但是核心的部分都已经记录下来!

4、客户端的主要代码如下:

String end = "\r\n";
String twoHyphens = "--";
String boundary = "*******";
DataOutputStream ds = null;
FileInputStream fis =null;
try {
System.out.println("NativeMethod");
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");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "utf-8");
con.setRequestProperty("Content-type",
"multipart/form-data;boundary=" + boundary);
/** 设置dataOutputStream */
ds = new DataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disponsition: form-data; "
+ "name=\"file1\"; filenname=\"" + newName + "\"" + end);
ds.writeBytes(end);

// 取得文件的FileInputStream
fis = new FileInputStream(path);
/* 设置每次写入1024bytes */
byte[] buffer = new byte[1024];
int length = -1;
// 从文件读取数据至缓存区
while ((length = fis.read(buffer)) != -1) {
/* 将资料写入dataOutputStream */
ds.write(buffer, 0, length);
}
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + end);
ds.flush();

// 取得Response的内容
InputStream is = con.getInputStream();
int ch;
StringBuffer b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
System.out.println("toast part");
Toast.makeText(activity, b.toString() + "上传成功",
Toast.LENGTH_SHORT).show();
ds.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(activity, "图片上传失败!",
Toast.LENGTH_SHORT).show();
throw new RuntimeException(e);
} /*finally {
// 关闭流
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}*/
}

这里我需要说明一下,这些代码也是在我参考别人写的代码的基础上修改过来的,希望可以和大家分享!!
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics