在好例子网,分享、交流、成长!
您当前所在位置:首页Java 开发实例Android平台开发 → android 图片上传源码(含服务器端接收代码)

android 图片上传源码(含服务器端接收代码)

Android平台开发

下载此实例
  • 开发语言:Java
  • 实例大小:0.73M
  • 下载次数:27
  • 浏览次数:401
  • 发布时间:2016-11-09
  • 实例类别:Android平台开发
  • 发 布 人:ycyxs
  • 文件格式:.zip
  • 所需积分:2
 相关标签: 上传 图片 图片上传

实例介绍

【实例简介】

【实例截图】

【核心代码】

服务器端代码:

package com.easyway.fileupload;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
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.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
 * 文件上传的Serlvet类
 * 
 * Servlet implementation class FileImageUploadServlet
 * 
 *    此处的文件上传比较简单没有处理各种验证,文件处理的错误等。
 * 如果需要处理,请修改源代码即可。
 * @Title: 
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-7-22
 * @author  longgangbai
 * @version 1.0
 */
public class FileImageUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private ServletFileUpload upload;
	private final long MAXSize = 4194304*2L;//4*2MB
	private String filedir=null;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileImageUploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * 设置文件上传的初始化信息
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		FileItemFactory factory = new DiskFileItemFactory();// Create a factory for disk-based file items
		this.upload = new ServletFileUpload(factory);// Create a new file upload handler
		this.upload.setSizeMax(this.MAXSize);// Set overall request size constraint 4194304
		filedir=config.getServletContext().getRealPath("images");
		System.out.println("filedir=" filedir);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		PrintWriter out=response.getWriter();
		try {
			List<FileItem> items = this.upload.parseRequest(request);
			if(items!=null	&& !items.isEmpty()){
				for (FileItem fileItem : items) {
					String filename=fileItem.getName();
					String filepath=filedir File.separator filename;
					System.out.println("文件保存路径为:" filepath);
					File file=new File(filepath);
					InputStream inputSteam=fileItem.getInputStream();
					BufferedInputStream fis=new BufferedInputStream(inputSteam);
				    FileOutputStream fos=new FileOutputStream(file);
				    int f;
				    while((f=fis.read())!=-1)
				    {
				       fos.write(f);
				    }
				    fos.flush();
				    fos.close();
				    fis.close();
					inputSteam.close();
					System.out.println("文件:" filename "上传成功!");
				}
			}
			System.out.println("上传文件成功!");
			out.write("上传文件成功!");
		} catch (FileUploadException e) {
			e.printStackTrace();
			out.write("上传文件失败:" e.getMessage());
		}
	}

}

android端代码:



public static String uploadFile(File file,String RequestURL)
{
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)
{
/**
* 当文件不为空,把文件包装并且上传
*/
OutputStream outputSteam=conn.getOutputStream();

DataOutputStream dos = new DataOutputStream(outputSteam);
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
/**
* 这里重点注意:
* name里面的值为服务器端需要key   只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名的   比如:abc.png  
*/

sb.append("Content-Disposition: form-data; name=\"img\"; 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[1024];
int len = 0;
while((len=is.read(bytes))!=-1)
{
dos.write(bytes, 0, len);
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX BOUNDARY PREFIX LINE_END).getBytes();
dos.write(end_data);
dos.flush();
/**
* 获取响应码  200=成功
* 当响应成功,获取响应的流  
*/
int res = conn.getResponseCode();  
Log.e(TAG, "response code:" res);
if(res==200)
{
    return SUCCESS;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

实例下载地址

android 图片上传源码(含服务器端接收代码)

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

第 1 楼 zht_zinan 发表于: 2016-11-16 10:02 45
这个应该还是很实用的。

支持(0) 盖楼(回复)

发表评论

(您的评论需要经过审核才能显示)

查看所有1条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警