android 上传图片到服务器Tomcat(Struts2)
在做android开发的时候,有时你会用到图片的上传功能,在我的android项目中,我是选中图片,点击上传多张图片
android客户端上传图片部分的代码如下:
package com.example.myphotos.utils; import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID; import android.util.Log; public class UploadUtil {
private static final String TAG = "uploadFile";
private static final int TIME_OUT = * ; // 超时时间
private static final String CHARSET = "utf-8"; // 设置编码 /**
* 上传文件到服务器
*
* @param file
* 需要上传的文件
* @param RequestURL
* 请求的rul
* @return 返回响应的内容
*/
public static int uploadFile(File file, String RequestURL) {
int res = ;
String result = null;
String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; // 内容类型 try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true); // 允许输入流
conn.setDoOutput(true); // 允许输出流
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST"); // 请求方式
conn.setRequestProperty("Charset", CHARSET); // 设置编码
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="
+ BOUNDARY); if (file != null) {
/**
* 当文件不为空时执行上传
*/
DataOutputStream dos = new DataOutputStream(
conn.getOutputStream());
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
/**
* 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名
*/ sb.append("Content-Disposition: form-data; name=\"file\"; filename=\""
+ file.getName() + "\"" + LINE_END);
sb.append("Content-Type: application/octet-stream; charset="
+ CHARSET + LINE_END);
sb.append(LINE_END);
dos.write(sb.toString().getBytes());
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[];
int len = ;
while ((len = is.read(bytes)) != -) {
dos.write(bytes, , len);
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
.getBytes();
dos.write(end_data);
dos.flush();
/**
* 获取响应码 200=成功 当响应成功,获取响应的流
*/
res = conn.getResponseCode();
Log.e(TAG, "response code:" + res);
if (res == ) {
Log.e(TAG, "request success");
InputStream input = conn.getInputStream();
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -) {
sb1.append((char) ss);
}
result = sb1.toString();
Log.e(TAG, "result : " + result);
} else {
Log.e(TAG, "request error");
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
}
服务器段的代码如下:
服务器端用的Struts2
package www.csdn.image; import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random; import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest; import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport; /**
* ImagesAction 2013-6-18 下午9:02:58
*
* @author 乔晓松
*
*/
public class ImagesAction extends ActionSupport { /**
*
*/
private static final long serialVersionUID = 1L; public List<String> list = new ArrayList<String>();
private File file;
private String fileContentType;
private String fileFileName; public File getFile() {
return file;
} public void setFile(File file) {
this.file = file;
} public String getFileContentType() {
return fileContentType;
} public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
} public String getFileFileName() {
return fileFileName;
} public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
} public List<String> getList() {
return list;
} public String httpAllImages() {
String path = ServletActionContext.getServletContext().getRealPath(
"images");
// System.out.println(path);
File filePath = new File(path);
File[] files = filePath.listFiles();
for (int i = ; i < files.length; i++) {
File file = files[i];
if (!file.isDirectory()) {
String fileName = file.getName();
String img = fileName.substring(fileName.lastIndexOf(".") + );
if ("jpg".equals(img) || "jpeg".equals(img)
|| "gif".equals(img) || "png".equals(img)) { list.add(fileName);
}
}
}
System.out.println(list.size());
return "images";
} @SuppressWarnings("deprecation")
public String uploadFile() {
System.out.println("-----------------");
System.out.println(fileFileName + "------------------" + file.length());
try {
FileInputStream fis = new FileInputStream(file);
String photospath = ServletActionContext.getRequest().getRealPath(
"photos");
System.out.println(photospath);
File fs = new File(photospath, fileFileName);
FileOutputStream fos = new FileOutputStream(fs);
int len = ;
byte[] buffer = new byte[]; while ((len = fis.read(buffer)) != -) {
fos.write(buffer, , len);
}
fos.flush();
fos.close();
fis.close(); } catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} return "uploadfile";
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<include file="struts-constant.xml"></include>
<package name="test" namespace="/csdn" extends="json-default">
<action name="ImagesAction_*" class="www.csdn.image.ImagesAction"
method="{1}">
<result name="images" type="json">list</result>
<result name="uploadfile"></result>
</action>
</package>
</struts>
图片上传:http://topmanopensource.iteye.com/blog/1605238(有例子)。
http://blog.csdn.net/lmj623565791/article/details/23781773
android 上传图片到服务器Tomcat(Struts2)的更多相关文章
- Java乔晓松-android中上传图片到服务器Tomcat(Struts2)
在做android开发的时候,有时你会用到图片的上传功能,在我的android项目中,我是选中图片,点击上传多张图片 android客户端上传图片部分的代码如下: package com.exampl ...
- Android 上传图片到服务器二--------调用相机7.0以上权限问题
[目录] (一)上传图片到服务器一 ---------------------------------Android代码 (二)上传图片到服务器二--------------------------- ...
- Android 上传图片到服务器 okhttp一
[目录] (一)上传图片到服务器一 ---------------------------------Android代码 (二)上传图片到服务器二--------------------------- ...
- Android上传图片到服务器
一.android需要导入异步请求的jar包 AsyncHttpClient public static void reg(final Context cont,Bitmap photodata,S ...
- android上传图片至服务器
本实例实现了android上传手机图片至服务器,服务器进行保存 服务器servlet代码publicvoid doPost(HttpServletRequest request, HttpServle ...
- Android上传图片到服务器,服务端利用.NET WCFRest服务读取文件的解决方案
在项目中遇到要将Android设备拍摄的照片上传的服务器,将文件保存在服务器本地的文件夹中,数据库中保存的是图片文件名.整个上传是将图片生成二进制流通过HTTP请求上传到服务端,服务端是基于.NET环 ...
- 通过android 客户端上传图片到服务器
昨天,(在我的上一篇博客中)写了通过浏览器上传图片到服务器(php),今天将这个功能付诸实践.(还完善了服务端的代码) 不试不知道,原来通过android 向服务端发送图片还真是挺麻烦的一件事. 上传 ...
- Android服务器——TomCat服务器的搭建
Android服务器--TomCat服务器的搭建 作为一个开发人员,当然是需要自己调试一些程序的,这个时候本地的服务器就十分方便了,一般都会使用TomCat或者IIS服务器,IIS就比较简单了,其实t ...
- 转: android之虚拟机访问tomcat服务器资源
最近在研究Android虚拟机访问tomcat服务器资源,所以找了个时间写下这篇博客和大家分享一下心得. 其实Android虚拟机访问tomcat服务器非常的简单,只要不要弄错IP地址就可以访问tom ...
随机推荐
- Amazon S3 上传文件 SSL23_GET_SERVER_HELLO握手错误
题外话:今天偶尔来逛逛,发现我真是懒到家了.居然有半年前的留言我都没有来看过,真对不起留言的同学,希望他的问题已经解决了. 这两三天一直被亚马逊S3上传文件的问题困扰着,直到昨天晚上终于搞定了,工作群 ...
- SQL语句对应的LINQ和Lambda语句
1. 查询Student表中的所有记录的Sname.Ssex和Class列.select sname,ssex,class from studentLinq: from s in Student ...
- 在sql2008的实例 中 编写存储过程 读取 版本为sql2005 的实例 中的某个数据库里的数据
--创建链接服务器 exec sp_addlinkedserver 'ITSV ', ' ', 'SQLOLEDB ', '远程服务器名或ip地址 ' exec sp_addlinkedsrvl ...
- html 包含一个公共文件
<SCRIPT> $(document).ready(function(){ $("#foo").load("top.html"); setTime ...
- 在自定义的web监听器中嵌入web中的定时事件
在 http://www.cnblogs.com/myadmin/p/4806265.html 中说明了自定义web监听器的一些东西. 本文中的web定时任务也基于上篇文章的自定义web监听器. 新建 ...
- c语言学习之基础知识点介绍(一):输出语句和变量简单介绍
本系列是为了学习ios做准备的,也能作为c语言入门的教程看看. c语言的程序结构: 1.顺序结构:自上而下依次执行. 2.分支结构:程序有选择的执行某段代码或者不执行某段代码. 3.循环结构:程序循环 ...
- A题笔记(10)
No.1390 代码:https://code.csdn.net/snippets/191965 另一版本:https://code.csdn.net/snippets/192009 考察点有两个: ...
- 在jsp中用EL 表达来获取表单中的参数
在一个JSP页面转到另一个JSP页面时,对表单中的参数用EL表达式提取为: <form action="sampleJsp.jsp" method="po ...
- 淘宝链接中的spm参数
什么是SPM SPM是淘宝社区电商业务(xTao)为外部合作伙伴(外站)提供的一套跟踪引导成交效果数据的解决方案. 下面是一个跟踪点击到宝贝详情页的引导成交效果数据的SPM示例: http://det ...
- Object-C 类实现
这篇为Object-C添加方法的后续. 这里我们应该在类的实现(.m)文件中写 #import "Photo.h" @implementation Photo - (NSStrin ...