android 文件上传下载

来源:互联网 发布:花开花落知多少下一句 编辑:程序博客网 时间:2024/06/07 18:57

java 后台:


下载servlet:

package com.wenga.servlet;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.wenga.util.DBHelp;


public class FileDownServlet extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html; charset=utf-8";


    //Initialize global variables
    public void init() throws ServletException {
    }


    //Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        response.setContentType(CONTENT_TYPE);
        //得到下载文件的名字
        String uploadPath= request.getSession().getServletContext().getRealPath("");
uploadPath=uploadPath.replaceAll("\\\\", "/")+"/headImage/";
        //String filename=request.getParameter("filename");

Integer uid=Integer.valueOf(request.getParameter("uid"));
System.out.println("uid:  "+uid);

String sql="SELECT headUrl from t_user where uid="+uid;

       
//        //解决中文乱码问题
//        String filename=new String(request.getParameter("filename").getBytes("iso-8859-1"),"utf-8");

//创建file对象
File file=null;
String filenameString=DBHelp.findBySql(sql);
if(filenameString!=null){
file=new File(uploadPath+DBHelp.findBySql(sql));
}else{
file=new File(uploadPath+"temp.png");
}




        //设置response的编码方式
        response.setContentType("application/x-msdownload");


        //写明要下载的文件的大小
        response.setContentLength((int)file.length());


        //设置附加文件名
       // response.setHeader("Content-Disposition","attachment;filename="+filename);
       
//        //解决中文乱码
//    response.setHeader("Content-Disposition","attachment;filename="+new String
//
//(filename.getBytes("utf-8"),"iso-8859-1"));       


        //读出文件到i/o流
        FileInputStream fis=new FileInputStream(file);
        BufferedInputStream buff=new BufferedInputStream(fis);


        byte [] b=new byte[1024];//相当于我们的缓存


        long k=0;//该值用于计算当前实际下载了多少字节


        //从response对象中得到输出流,准备下载


        OutputStream myout=response.getOutputStream();


        //开始循环下载


        while(k<file.length()){


            int j=buff.read(b,0,1024);
            k+=j;


            //将b中的数据写到客户端的内存
            myout.write(b,0,j);


        }


        //将写入到客户端的内存的数据,刷新到磁盘
        myout.flush();


    }


    //Process the HTTP Post request
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        doGet(request, response);
    }


    //Clean up resources
    public void destroy() {
    }
}





上传servlet:


package com.wenga.servlet;


import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


import com.wenga.util.DBHelp;


/**
 * 学生照片批量上传servlet
 * @author chengxuyuan
 *
 */
@SuppressWarnings("serial")
public class FileUpload extends HttpServlet {

private String uid;

private int maxPostSize = 100 * 1024 * 1024;


public FileUpload() {
super();
}


public void destroy() {
super.destroy();
}


protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// ApplicationContext cpa=new ClassPathXmlApplicationContext("applicationContext.xml");
// parentService=(ParentService) cpa.getBean("parentDao");
// WebApplicationContext wbc=WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
// CarcleanServiceImpl parentService=wbc.getBean(CarcleanServiceImpl.class);

if(request.getParameter("uid")!=null){
uid=request.getParameter("uid");
}

System.out.println( uid);

String uploadPath=request.getSession().getServletContext().getRealPath("");
uploadPath=uploadPath.replaceAll("\\\\", "/")+"/headImage/";
System.out.println("Access!  路径"+uploadPath );

File f=new File(uploadPath);
if(!(f.exists())){
f.mkdirs();
}


response.setContentType("text/html;charset=UTF-8");
// PrintWriter out = response.getWriter();

// out.print("已连接上!");


// 保存文件到服务器中
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4096);
ServletFileUpload upload = new ServletFileUpload(factory);

upload.setSizeMax(maxPostSize);

try {
List fileItems = upload.parseRequest(request);
Iterator iter = fileItems.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String name = item.getName();
System.out.println("文件名: "+name);

// user.setHeadUrl(name);

// carcleanService.addOrUpdate(user);

String sql="UPDATE t_user set headUrl='"+name+"' WHERE uid="+uid;
DBHelp.saveImageName(sql);

//如果原来就有照片,就把原来的照片删掉
if(name!=null){
File file=new File(uploadPath + name);
if(file.exists()){
file.delete();
}
}

try {
item.write(new File(uploadPath + name));
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}


public String getUid() {
return uid;
}


public void setUid(String uid) {
this.uid = uid;
}



}



web.xml:


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!-- 解决hibernate lazy策略使用问题,用spring集成的处理类 -->
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>


<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>


<!-- 解决字符集处理问题 用spring集成的处理类 -->
<filter>
<filter-name>Spring character encoding filter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>


<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>Spring character encoding filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>


<!-- 开启监听 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>


<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<!-- 照片上传 -->
<servlet>
    <servlet-name>FileUpload</servlet-name>
    <servlet-class>com.wenga.servlet.FileUpload</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>FileUpload</servlet-name>
    <url-pattern>/uplodPhotoes.let</url-pattern>
  </servlet-mapping>
  
  <!-- 照片下载 -->
<servlet>
    <servlet-name>FileDownload</servlet-name>
    <servlet-class>com.wenga.servlet.FileDownServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>FileDownload</servlet-name>
    <url-pattern>/downPhotoes.let</url-pattern>
  </servlet-mapping>
</web-app>


jsp: 上传: 


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
  </head>
  
 <body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="uplodPhotoes.let?uid=1" method="post"
                        enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>



android 下载:


package com.ys.carclean.activity;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;


import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;


import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.widget.ImageView;


import com.ys.carclean.R;


public class ImageActivity extends Activity {

ImageView iView;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);

iView=(ImageView) findViewById(R.id.iv);

new Thread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
try {
HttpPost post = new HttpPost("http://192.168.0.105:8080/study/downPhotoes.let?uid=1");


// 执行这个post请求 返回一个 response对象
HttpResponse resp = new DefaultHttpClient().execute(post);
if (resp.getStatusLine().getStatusCode() == 200) {


InputStream is = resp.getEntity().getContent();

byte[] buf;
try {
buf = readStream(is);
mBitmap = BitmapFactory.decodeByteArray(buf, 0, buf.length);// bitmap  
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Message message = new Message();
message.what = 1;
mHandler.sendMessage(message);


}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}
}).start();

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.image, menu);
return true;
}

private Bitmap mBitmap; 


private Handler mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
if(msg.what==1){
if(mBitmap!=null){
iView.setImageBitmap(mBitmap);
}
}
}
};


    /** 
     * Get data from stream 
     * @param inStream 
     * @return byte[] 
     * @throws Exception 
     */  
    public static byte[] readStream(InputStream inStream) throws Exception{  
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        byte[] buffer = new byte[1024];  
        int len = 0;  
        while( (len=inStream.read(buffer)) != -1){  
            outStream.write(buffer, 0, len);  
        }  
        outStream.close();  
        inStream.close();  
        return outStream.toByteArray();  
    }


}


android 上传:



package com.ys.carclean.activity;


import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;


import com.ys.carclean.R;


public class UplodActivity extends Activity {

private final static String ALBUM_PATH   
    = Environment.getExternalStorageDirectory() + "/download_test/";
    
private String newName ="image.jpg";
    private String actionUrl ="http://192.168.0.105:8080/study/uplodPhotoes.let?uid=1";
 
    private  File file111; 


 
/*组件*/
    private RelativeLayout switchAvatar;
private ImageView faceImage;


    private String[] items = new String[] { "选择本地图片", "拍照" };
    /*头像名称*/
    private static final String IMAGE_FILE_NAME = "faceImage.jpg";
    
    /* 请求码*/
    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int RESULT_REQUEST_CODE = 2;


    @Override
    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE); // 去掉标题
           setContentView(R.layout.activity_uplod);
            switchAvatar = (RelativeLayout) findViewById(R.id.switch_face_rl);
            faceImage = (ImageView) findViewById(R.id.face);
    //设置事件监听
           switchAvatar.setOnClickListener(listener);
    }


    private View.OnClickListener listener = new View.OnClickListener() {


            @Override
            public void onClick(View v) {
                    showDialog();
            }
    };
/**
 * 显示选择对话框
*/
    private void showDialog() {
            
            new AlertDialog.Builder(this)
                            .setTitle("设置头像")
                            .setItems(items, new DialogInterface.OnClickListener() {


                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                            switch (which) {
                                            case 0:
                                                    Intent intentFromGallery = new Intent();
                                                    intentFromGallery.setType("image/*"); // 设置文件类型
                                                   intentFromGallery
                                                                    .setAction(Intent.ACTION_GET_CONTENT);
                                                    startActivityForResult(intentFromGallery,
                                                                    IMAGE_REQUEST_CODE);
                                                    break;
                                            case 1:


                                                    Intent intentFromCapture = new Intent(
                                                                    MediaStore.ACTION_IMAGE_CAPTURE);
                                                    // 判断存储卡是否可以用,可用进行存储
                                                   if (Tools.hasSdcard()) {


                                                            intentFromCapture.putExtra(
                                                                            MediaStore.EXTRA_OUTPUT,
                                                                            Uri.fromFile(new File(Environment
                                                                                            .getExternalStorageDirectory(),
                                                                                            IMAGE_FILE_NAME)));
                                                    }


                                                    startActivityForResult(intentFromCapture,
                                                                    CAMERA_REQUEST_CODE);
                                                    break;
                                            }
                                    }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {


                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                    }
                            }).show();


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            switch (requestCode) {
            case IMAGE_REQUEST_CODE:
                    startPhotoZoom(data.getData());
                    break;
            case CAMERA_REQUEST_CODE:
                    if (Tools.hasSdcard()) {
                            File tempFile = new File(
                                            Environment.getExternalStorageDirectory()
                                                            + IMAGE_FILE_NAME);
                            startPhotoZoom(Uri.fromFile(tempFile));
                    } else {
                            Toast.makeText(UplodActivity.this, "未找到存储卡,无法存储照片!",
                                            Toast.LENGTH_LONG).show();
                    }


                    break;
            case RESULT_REQUEST_CODE:
                    if (data != null) {
                            getImageToView(data);
                    }
                    break;
            }
            super.onActivityResult(requestCode, resultCode, data);
    }


    /**
     * 裁剪图片方法实现
    * 
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {


            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(uri, "image/*");
            // 设置裁剪
           intent.putExtra("crop", "true");
            // aspectX aspectY 是宽高的比例
           intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            // outputX outputY 是裁剪图片宽高
           intent.putExtra("outputX", 320);
            intent.putExtra("outputY", 320);
            intent.putExtra("return-data", true);
            startActivityForResult(intent, 2);
    }


    /**
     * 保存裁剪之后的图片数据
    * 
     * @param picdata
     */
    private void getImageToView(Intent data) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                    Bitmap photo = extras.getParcelable("data");
                    
                    try {
saveFile(photo,"test.jpg");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
                    Drawable drawable = new BitmapDrawable(photo);
                    faceImage.setImageDrawable(drawable);
                    new Thread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
uploadFile();
}
}).start();
                    
            }
    }
    
    




    /* 上传文件至Server的方法 */
    private void 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(file111);
        /* 设置每次写入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 );
        }
        ds.close();
      }
      catch(Exception e)
      {
      }
    }


    
    /** 
     * 保存文件 
     * @param bm 
     * @param fileName 
     * @throws IOException 
     */  
    public void saveFile(Bitmap bm, String fileName) throws IOException {  
        File dirFile = new File(ALBUM_PATH);  
        if(!dirFile.exists()){  
            dirFile.mkdir();  
        }  
        file111 = new File(ALBUM_PATH + fileName);  
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file111));  
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);  
        bos.flush();  
        bos.close();  
    }
}




activity_upload.xml:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#F3F1DA"
    android:orientation="vertical" >


    <!-- title -->


    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:orientation="horizontal" >


        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="个人信息"
            android:textColor="@android:color/white" />
    </LinearLayout>


    <!-- image switch -->


    <RelativeLayout
        android:id="@+id/switch_face_rl"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="20dip"
        android:clickable="true" 
        android:padding="5dip" >


        <ImageView
            android:id="@+id/face"
            android:layout_width="42dip"
            android:layout_height="42dip"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="10dip"
             />


        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dip"
            android:layout_marginTop="5dip"
            android:layout_toRightOf="@id/face"
            android:layout_gravity="center"
            android:text="设置头像"
            android:textColor="@android:color/black" /> 
    </RelativeLayout>


</LinearLayout>



AndroidManifest.xml:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ys.carclean"
    android:versionCode="1"
    android:versionName="1.0" >


    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="10" />


    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.ys.carclean.activity.UplodActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- <activity -->
        <!-- android:name="com.ys.carclean.activity.ImageActivity" -->
        <!-- android:label="@string/title_activity_image" > -->
        <!-- </activity> -->
        <activity
            android:name="com.ys.carclean.activity.ImageActivity"
            >
        </activity>
    </application>


</manifest>



0 0