Android+struts2实现文件图片上传,附源码(侧重服务端开发)

来源:互联网 发布:linux vi 行号 编辑:程序博客网 时间:2024/05/22 12:33

前言

项目中遇到Android手机聊天的图片、语音文件保存到服务器,网上搜索一下大概3种思路:

1.servlet实现,有很多文章,利用DiskFileUpload

2.使用smartupload未学习

3.利用strtus2自带的文件上传功能。

由于strtus2已广泛应用与企业应用,且上手较快,学习成本低、配置简单。文件上传功能已封装,简单易用,故毫不犹豫选择他。

网上这方面的资料不少,但很多重复的,且比较乱,新手可能很难找到自己想要的。总算自己捣鼓半天完成了功能,整理做下笔记,供大家参考。最后附上源码

 

Android客户端

//要用到三个东东来做Post:HttpClient,httpPost,MultipartEntityHttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter( CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1 );HttpPost httpPost = new HttpPost( "http://localhost:8680/upload/chat/uploadFile" );MultipartEntity postEntity = new MultipartEntity();// 字符用StringBodyString fileName = "2.jpg";ContentBody cbFileName;cbFileName = new StringBody( fileName );// 文件用FileBody,并指定文件类型File file = new File( "D:\\FTP\\2.jpg");ContentBody cbFileData = new FileBody( file, "image/jpg" );// 把上面创建的这些Body全部加到Entity里面去。// 注意他们的key,这些key在Struts2服务器端Action的代码里必须保持一致!!postEntity.addPart( "fileName", cbFileName );postEntity.addPart( "fileData", cbFileData );httpPost.setEntity( postEntity );// 下面这句话就把数据提交到服务器去了HttpResponse response = httpClient.execute( httpPost );

 

服务端struts2

配置web.xml、引入相应jar包、等本文不展开论述,

struts.xml配置

<package name="chat" namespace="/chat" extends="struts-default">    <action name="uploadFile" class="com.tch.action.FileUploadAction" method="upload">        </action>    </package>

贴上Action类

// 注意这些变量名,看见了没? 和Struts2的FormBean是一样的。// 要和客户端添加字段时的关键字保持一致!!private String fileName = null;private String fileData = null;//针对每个字段的关键字,下面的这些Set方法必须一个不少,否则你什么也得不到public void setFileName(String fileName) {this.fileName = fileName;}public void setFileData(String fileData) {this.fileData = fileData;}
public String upload(){String webappPath = findServerPath();//path=D:\apache-tomcat-6.0.36\webapps\dqapi\//String path = ServletActionContext.getServletContext().getRealPath("/");//appPath=/dqapi//String appPath = ServletActionContext.getServletContext().getContextPath();String chatFile_path = ServletActionContext.getServletContext().getInitParameter("UPLOAD_CHAT_FILE_PATH");FileCopyUtil util = new FileCopyUtil();String[] array = fileName.split("\\.");String fileType = array[array.length-1];//String destDir = path.replace(appPath, chatFile_path);String destDir = webappPath + chatFile_path;//先获取HttpServletResponse    HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get( ServletActionContext.HTTP_RESPONSE );    //打开数据流,把要给客户端返回的数据写进数据流    OutputStream writer = null;    ......        // 这里不用再返回其他字符串了。    // 客户端接收的不是这里返回的数据,这个是显示结果网页才会用到的返回值。    return null;}


 

 

 将用户上传文件与web项目本身分离

项目路径D:\apache-tomcat-6.0.36\webapps\upload

保存上传的文件到webapps目录下指定位置
 

文件拷贝代码如下

public String copyFile(String fileType,String fileData,String destDir) throws IOException{Date date = new Date();String dirName = new SimpleDateFormat("yyyyMMdd").format(date);String newFileName = new SimpleDateFormat("yyyyMMddHHmmss_SSS").format(date);//destDir的值D:/apache-tomcat-6.0.36/webapps/chat/String dirPath = destDir+dirName;File dir = new File(dirPath);if(!dir.exists()  && !dir.isDirectory()){//目录不存在,创建目录dir.mkdir();}String newFilePath = dirPath+"/"+newFileName+"."+fileType;FileInputStream in=new FileInputStream(new File(fileData));FileOutputStream out=new FileOutputStream(newFilePath);int length=2097152;byte[] buffer=new byte[length];while(true){int ins=in.read(buffer);if(ins==-1){in.close();out.flush();out.close();return newFilePath;}elseout.write(buffer,0,ins);}}

源码0积分下载地址以及调试过程

http://download.csdn.net/detail/qq964166471/6912621

 

模拟Android端发起文件上传请求,进入服务端Action,观察fileData,发现指向一个tmp文件,此时struts已接受到客户端上传的文件,我们需要做的紧紧是将文件保存到我们希望的位置

最后客户端从response中取出服务器的返回数据

加上http://localhost:8680/chat/20140211/20140211142224_984.jpg便可访问新上传的图片了

 

 测试结果:

支持图片、文本、amr上传,完成。

 

 

欢迎转载,请注明出自http://blog.csdn.net/qq964166471/article/details/19073761

0 0