1. android 上传图片到服务器
final Map<String, String> params = new HashMap<String, String>();
params.put("send_userId", String.valueOf(id));
params.put("send_email", address);
params.put("send_name", name);
params.put("receive_email", emails);
final Map<String, File> files = new HashMap<String, File>();
files.put("uploadfile", file);
final String request = UploadUtil.post(requestURL, params, files);
2. android里的图片怎样上传到服务器并返回显示在手机上求具体的代码急用!!!
这个图片存放的位置是根据你的图片来源而定的。一般是放在sdcard下的某个目录下的,我基本看明白你写的需求。我来给你说下思路:服务端(android手机)这边需要写个工具类,来遍历SD卡下的文件,只显示jpg和png的图片。主类中有个按钮来添加图片,还有一个按钮是用来上传图片,然后写个监听,用来接收服务端发回的消息。文件的传输就不用我细说了吧...服务端这边写个监听来接收客户端发来的消息,保存发过来的数据流。至于手机上能显示这张图片,只要在写个imageview,把图片资源加载上就ok啦,你可以去网上搜索一下“sd上的文件上传”,有很多类似的文章和代码,可供学习的,有什么不懂的再问吧^_^
3. android 怎么写上传图片代码
请问图片是放在android手机的哪个地方,要在android手机怎么显示返回呢,主类中有个按钮来添加图片,还有一个按钮是用来上传图片,然后写个监听,
4. android如何实现图片批量上传
首先,以下架构下的批量文件上传可能会失败或者不会成功:
1.android客户端+springMVC服务端:服务端采用org.springframework.web.multipart.MultipartHttpServletRequest作为批量上传接收类,这种搭配下的批量文件上传会失败,最终服务端只会接受到一个文件,即只会接受到第一个文件。可能因为MultipartHttpServletRequest对servlet原本的HttpServletRequest类进行封装,导致批量上传有问题。
2.android客户端+strutsMVC服务端:
上传成功的方案:
采用android客户端+Servlet(HttpServletRequest)进行文件上传。
Servlet端代码如下:
[java] view plainprint?
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try
{
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext())
{
FileItem item = (FileItem) itr.next();
if (item.isFormField())
{
System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8"));
}
else
{
if (item.getName() != null && !item.getName().equals(""))
{
System.out.println("上传文件的大小:" + item.getSize());
System.out.println("上传文件的类型:" + item.getContentType());
// item.getName()返回上传文件在客户端的完整路径名称
System.out.println("上传文件的名称:" + item.getName());
File tempFile = new File(item.getName());
// 上传文件的保存路径
File file = new File(sc.getRealPath("/") + savePath, tempFile.getName());
item.write(file);
request.setAttribute("upload.message", "上传文件成功!");
} else
{
request.setAttribute("upload.message", "没有选择上传文件!");
}
}
}
}
catch (FileUploadException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
request.setAttribute("upload.message", "上传文件失败!");
}
request.getRequestDispatcher("/uploadResult.jsp").forward(request, response);
android端代码如下:
[java] view plainprint?
public class SocketHttpRequester {
/**
*多文件上传
* 直接通过HTTP协议提交数据到服务器,实现如下面表单提交功能:
* <FORM METHOD=POST ACTION="http://192.168.1.101:8083/upload/servlet/UploadServlet" enctype="multipart/form-data">
<INPUT TYPE="text" NAME="name">
<INPUT TYPE="text" NAME="id">
<input type="file" name="imagefile"/>
<input type="file" name="zip"/>
</FORM>
* @param path 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.iteye.cn或http://192.168.1.101:8083这样的路径测试)
* @param params 请求参数 key为参数名,value为参数值
* @param file 上传文件
*/
public static boolean post(String path, Map<String, String> params, FormFile[] files) throws Exception{
final String BOUNDARY = "---------------------------7da2137580612"; //数据分隔线
final String endline = "--" + BOUNDARY + "--\r\n";//数据结束标志
int fileDataLength = 0;
for(FormFile uploadFile : files){//得到文件类型数据的总长度
StringBuilder fileExplain = new StringBuilder();
fileExplain.append("--");
fileExplain.append(BOUNDARY);
fileExplain.append("\r\n");
fileExplain.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");
fileExplain.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");
fileExplain.append("\r\n");
fileDataLength += fileExplain.length();
if(uploadFile.getInStream()!=null){
fileDataLength += uploadFile.getFile().length();
}else{
fileDataLength += uploadFile.getData().length;
}
}
StringBuilder textEntity = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {//构造文本类型参数的实体数据
textEntity.append("--");
textEntity.append(BOUNDARY);
textEntity.append("\r\n");
textEntity.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n");
textEntity.append(entry.getValue());
textEntity.append("\r\n");
}
//计算传输给服务器的实体数据总长度
int dataLength = textEntity.toString().getBytes().length + fileDataLength + endline.getBytes().length;
URL url = new URL(path);
int port = url.getPort()==-1 ? 80 : url.getPort();
Socket socket = new Socket(InetAddress.getByName(url.getHost()), port);
OutputStream outStream = socket.getOutputStream();
//下面完成HTTP请求头的发送
String requestmethod = "POST "+ url.getPath()+" HTTP/1.1\r\n";
outStream.write(requestmethod.getBytes());
String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n";
outStream.write(accept.getBytes());
String language = "Accept-Language: zh-CN\r\n";
outStream.write(language.getBytes());
String contenttype = "Content-Type: multipart/form-data; boundary="+ BOUNDARY+ "\r\n";
outStream.write(contenttype.getBytes());
String contentlength = "Content-Length: "+ dataLength + "\r\n";
outStream.write(contentlength.getBytes());
String alive = "Connection: Keep-Alive\r\n";
outStream.write(alive.getBytes());
String host = "Host: "+ url.getHost() +":"+ port +"\r\n";
outStream.write(host.getBytes());
//写完HTTP请求头后根据HTTP协议再写一个回车换行
outStream.write("\r\n".getBytes());
//把所有文本类型的实体数据发送出来
outStream.write(textEntity.toString().getBytes());
//把所有文件类型的实体数据发送出来
for(FormFile uploadFile : files){
StringBuilder fileEntity = new StringBuilder();
fileEntity.append("--");
fileEntity.append(BOUNDARY);
fileEntity.append("\r\n");
fileEntity.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");
fileEntity.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");
outStream.write(fileEntity.toString().getBytes());
if(uploadFile.getInStream()!=null){
byte[] buffer = new byte[1024];
int len = 0;
while((len = uploadFile.getInStream().read(buffer, 0, 1024))!=-1){
outStream.write(buffer, 0, len);
}
uploadFile.getInStream().close();
}else{
outStream.write(uploadFile.getData(), 0, uploadFile.getData().length);
}
outStream.write("\r\n".getBytes());
}
//下面发送数据结束标志,表示数据已经结束
outStream.write(endline.getBytes());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
if(reader.readLine().indexOf("200")==-1){//读取web服务器返回的数据,判断请求码是否为200,如果不是200,代表请求失败
return false;
}
outStream.flush();
outStream.close();
reader.close();
socket.close();
return true;
}
/**
*单文件上传
* 提交数据到服务器
* @param path 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.itcast.cn或http://192.168.1.10:8080这样的路径测试)
* @param params 请求参数 key为参数名,value为参数值
* @param file 上传文件
*/
public static boolean post(String path, Map<String, String> params, FormFile file) throws Exception{
return post(path, params, new FormFile[]{file});
}
}
5. android图片上传的问题
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 1);
然后在重写activity里面的onActivityResult方法,获取到你选择的图片的uri,uri=data.getData();
你可以试下,我是这样实现的!
6. 怎样在android系统中上传图片,信息。以及修改信息,这些代码
我一般都是通过遍历集合的方式来上传图片。而且一般都不会去管这个上传的顺序,只需要服务端按你需要返回数据就可以了
7. android一次上传多张图片,我的代码如下,我希望只访问一次服务器,上传多张图片,求大神指导!
将所有图片放在一个数组中,,使用轮询,将整个数组里的内容全部上传即可,代码有点多,我就不写了,你可以在网上搜到的
8. android 如何使用HTTP上传图片到服务器指定路劲下,求源码 邮箱 [email protected]
安卓有专门的ftp应用啊
你去找一个 就可以了啊
和一般的ftp软件一样的啊
额 HTTP啊 看错了
那就不知道了 不知道一般的网站的上传代码 可不可以用
9. android上传图片到服务器,求服务器那边和android的Activity的完整代码。
服务器端servlet代码:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取输入流,是HTTP协议中的实体内容
ServletInputStream sis=request.getInputStream();
File file = new File(request.getSession().getServletContext().getRealPath("/img/"),"img_"+0+".jpg");
for (int imgnum = 0;file.exists();imgnum++)
{
file = new File(request.getSession().getServletContext().getRealPath("/img/"),"img_"+imgnum+".jpg");
}
//缓冲区
byte buffer[]=new byte[1024];
FileOutputStream fos=new FileOutputStream(file);
int len=sis.read(buffer, 0, 1024);
//把流里的信息循环读入到文件中
while( len!=-1 )
{
fos.write(buffer, 0, len);
len=sis.readLine(buffer, 0, 1024);
}
fos.close();
sis.close();
}
android客户端代码:
public static void uploadFile(String imageFilePath)
{
String actionUrl = "http://192.168.1.32:8080/UploadServer/ImageServlet";
try
{
URL url =new URL(actionUrl);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
DataOutputStream ds = new DataOutputStream(con.getOutputStream());
File file = new File(imageFilePath);
FileInputStream fStream = new FileInputStream(file);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
while((length = fStream.read(buffer)) != -1)
{
ds.write(buffer, 0, length);
}
fStream.close();
ds.flush();
InputStream is = con.getInputStream();
int ch;
StringBuffer b =new StringBuffer();
while( ( ch = is.read() ) != -1 )
{
b.append( (char)ch );
}
ds.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
10. 在Android端使用socket传输图片到java服务器,求源代码
/**
*思想:
1.直接将所有数据安装字节数组发送
2.对象序列化方式
*/
/**
*thread方式
*
*@authorAdministrator
*/
{
privatestaticfinalintFINISH=0;
privateButtonsend=null;
privateTextViewinfo=null;
privateHandlermyHandler=newHandler(){
@Override
publicvoidhandleMessage(Messagemsg){
switch(msg.what){
caseFINISH:
Stringresult=msg.obj.toString();//取出数据
if("true".equals(result)){
TestSocketActivity4.this.info.setText("操作成功!");
}else{
TestSocketActivity4.this.info.setText("操作失败!");
}
break;
}
}
};
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_test_sokect_activity4);
//StrictMode.setThreadPolicy(newStrictMode.ThreadPolicy.Builder()
//.detectDiskReads().detectDiskWrites().detectNetwork()
//.penaltyLog().build());
//StrictMode.setVmPolicy(newStrictMode.VmPolicy.Builder()
//.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
//.penaltyLog().penaltyDeath().build());
this.send=(Button)super.findViewById(R.id.send);
this.info=(TextView)super.findViewById(R.id.info);
this.send.setOnClickListener(newSendOnClickListener());
}
{
@Override
publicvoidonClick(Viewv){
try{
newThread(newRunnable(){
@Override
publicvoidrun(){
try{
//1:
Socketclient=newSocket("192.168.1.165",9898);
//2:
ObjectOutputStreamoos=newObjectOutputStream(
client.getOutputStream());
//3:
UploadFilemyFile=SendOnClickListener.this
.getUploadFile();
//4:
oos.writeObject(myFile);//写文件对象
//oos.writeObject(null);//避免EOFException
oos.close();
BufferedReaderbuf=newBufferedReader(
newInputStreamReader(client
.getInputStream()));//读取返回的数据
Stringstr=buf.readLine();//读取数据
Messagemsg=TestSocketActivity4.this.myHandler
.obtainMessage(FINISH,str);
TestSocketActivity4.this.myHandler.sendMessage(msg);
buf.close();
client.close();
}catch(Exceptione){
Log.i("UploadFile",e.getMessage());
}
}
}).start();
}catch(Exceptione){
e.printStackTrace();
}
}
()throwsException{//包装了传送数据
UploadFilemyFile=newUploadFile();
myFile.setTitle("tangcco安卓之Socket的通信");//设置标题
myFile.setMimeType("image/png");//图片的类型
Filefile=newFile(Environment.getExternalStorageDirectory()
.toString()
+File.separator
+"Pictures"
+File.separator
+"b.png");
InputStreaminput=null;
try{
input=newFileInputStream(file);//从文件中读取
ByteArrayOutputStreambos=newByteArrayOutputStream();
bytedata[]=newbyte[1024];
intlen=0;
while((len=input.read(data))!=-1){
bos.write(data,0,len);
}
myFile.setContentData(bos.toByteArray());
myFile.setContentLength(file.length());
myFile.setExt("png");
}catch(Exceptione){
throwe;
}finally{
input.close();
}
returnmyFile;
}
}
}{
privateStringtitle;
privatebyte[]contentData;
privateStringmimeType;
privatelongcontentLength;
privateStringext;
publicStringgetTitle(){
returntitle;
}
publicvoidsetTitle(Stringtitle){
this.title=title;
}
publicbyte[]getContentData(){
returncontentData;
}
publicvoidsetContentData(byte[]contentData){
this.contentData=contentData;
}
publicStringgetMimeType(){
returnmimeType;
}
publicvoidsetMimeType(StringmimeType){
this.mimeType=mimeType;
}
publiclonggetContentLength(){
returncontentLength;
}
publicvoidsetContentLength(longcontentLength){
this.contentLength=contentLength;
}
publicStringgetExt(){
returnext;
}
publicvoidsetExt(Stringext){
this.ext=ext;
}
}
下边是服务端
publicclassMain4{
publicstaticvoidmain(String[]args)throwsException{
ServerSocketserver=newServerSocket(9898);//服务器端端口
System.out.println("服务启动........................");
booleanflag=true;//定义标记,可以一直死循环
while(flag){//通过标记判断循环
newThread(newServerThreadUtil(server.accept())).start();//启动线程
}
server.close();//关闭服务器
}
}
{
="D:"+File.separator+"myfile"
+File.separator;//目录路径
privateSocketclient=null;
privateUploadFileupload=null;
publicServerThreadUtil(Socketclient){
this.client=client;
System.out.println("新的客户端连接...");
}
@Override
publicvoidrun(){
try{
ObjectInputStreamois=newObjectInputStream(
client.getInputStream());//反序列化
this.upload=(UploadFile)ois.readObject();//读取对象//UploadFile需要和客户端传递过来的包名类名相同,如果不同则会报异常
System.out.println("文件标题:"+this.upload.getTitle());
System.out.println("文件类型:"+this.upload.getMimeType());
System.out.println("文件大小:"+this.upload.getContentLength());
PrintStreamout=newPrintStream(this.client.getOutputStream());//BufferedWriter
out.print(this.saveFile());//返回响应
// BufferedWriterwriter=null;
// writer.write("");
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
this.client.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
privatebooleansaveFile()throwsException{//负责文件内容的保存
/**
*java.util.UUID.randomUUID():
*UUID.randomUUID().toString()是javaJDK提供的一个自动生成主键的方法。UUID(Universally
*UniqueIdentifier)全局唯一标识符,是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的,
*是由一个十六位的数字组成
*,表现出来的形式。由以下几部分的组合:当前日期和时间(UUID的第一个部分与时间有关,如果你在生成一个UUID之后,
*过几秒又生成一个UUID,
*则第一个部分不同,其余相同),时钟序列,全局唯一的IEEE机器识别号(如果有网卡,从网卡获得,没有网卡以其他方式获得
*),UUID的唯一缺陷在于生成的结果串会比较长,字符串长度为36。
*
*UUID.randomUUID().toString()是javaJDK提供的一个自动生成主键的方法。UUID(Universally
*UniqueIdentifier)全局唯一标识符,是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的,
*是由一个十六位的数字组成,表现出来的形式
*/
Filefile=newFile(DIRPATH+UUID.randomUUID()+"."
+this.upload.getExt());
if(!file.getParentFile().exists()){
file.getParentFile().mkdir();
}
OutputStreamoutput=null;
try{
output=newFileOutputStream(file);
output.write(this.upload.getContentData());
returntrue;
}catch(Exceptione){
throwe;
}finally{
output.close();
}
}
}{
privateStringtitle;
privatebyte[]contentData;
privateStringmimeType;
privatelongcontentLength;
privateStringext;
publicStringgetTitle(){
returntitle;
}
publicvoidsetTitle(Stringtitle){
this.title=title;
}
publicbyte[]getContentData(){
returncontentData;
}
publicvoidsetContentData(byte[]contentData){
this.contentData=contentData;
}
publicStringgetMimeType(){
returnmimeType;
}
publicvoidsetMimeType(StringmimeType){
this.mimeType=mimeType;
}
publiclonggetContentLength(){
returncontentLength;
}
publicvoidsetContentLength(longcontentLength){
this.contentLength=contentLength;
}
publicStringgetExt(){
returnext;
}
publicvoidsetExt(Stringext){
this.ext=ext;
}
}