备注:不同手机,配置不同,上传到服务器接收可能会报错;
1、点击事件:alerdialog;
final CharSequence[] items = { "相册" };
AlertDialog dlg = new AlertDialog.Builder(UserinfoActivity.this).setTitle("选择图片").setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
// 这里item是根据选择的方式,
// 在items数组里面定义了两种方式,拍照的下标为1所以就调用拍照方法
{
Intent getImage = new Intent( // 相册
Intent.ACTION_GET_CONTENT);
getImage.addCategory(Intent.CATEGORY_OPENABLE);
getImage.setType("image/*");
startActivityForResult(getImage, 0);
}
}
}).create();
dlg.show();
2、在onActivityResult方法中接受相册的数据:
/**
* 当选择的图片不为空的话,在获取到图片的途径
*/
Uri uri = data.getData();
try {
String[] pojo = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, pojo, null, null, null);
if (cursor != null) {
ContentResolver cr = this.getContentResolver();
int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(colunm_index);
/***
* 这里加这样一个判断主要是为了第三方的软件选择,比如:使用第三方的文件管理器的话, 你选择的文件就不一定是图片了,
* 这样的话,我们判断文件的后缀名 如果是图片格式的话,那么才可以
*/
if (path.endsWith("jpg") || path.endsWith("png")) {
picPath = path;
bitmap_pub = BitmapFactory.decodeStream(cr.openInputStream(uri));
//异步上传到服务器中
if (picPath != null && picPath.length() > 0) {
UploadFileTask uploadFileTask = new UploadFileTask(this);
uploadFileTask.setOnCheckedChanged(this);
uploadFileTask.execute(picPath, Data.user_Id);
Log.e("rrr", Data.icon_user_pub);
editsharepre("headerImgUrl", Data.icon_user_pub);
}
} else {
alert();
}
} else {
alert();
}
3、uploadFileTask异步上传的操作:
动作:将file文件上传到服务器、结果回调到前面的activity的页面;
public class UploadFileTask extends AsyncTask<String, Void, String> {
public static final String requestURL = Config.FileImageUploadServlet;
/**
* 可变长的输入参数,与AsyncTask.exucute()对应
*/
private ProgressDialog pdialog;
private static Activity context = null;
private onCheckedChanged listener;
public UploadFileTask(Activity ctx) {
this.context = ctx;
pdialog = ProgressDialog.show(context, "正在加载...", "系统正在处理您的请求");
}
//返回结果时的操作------(2)
@Override
protected void onPostExecute(String result) {
// 返回activity页面的内容
pdialog.dismiss();
if (UploadUtils.SUCCESS.equalsIgnoreCase(result)) {
listener.getisupload(true);
showresult("上传成功!");
} else {
listener.getisupload(false);
showresult("上传失败!");
}
}
@Override
protected void onPreExecute() {
}
@Override
protected void onCancelled() {
super.onCancelled();
}
//执行上传操作-----(1)
@Override
protected String doInBackground(String... params) {
String imgurl = params[0];
File file = new File(imgurl);
String userId = params[1].toString().trim();
return UploadUtils.uploadFile(file, requestURL + "?userId=" + userId);
}
@Override
protected void onProgressUpdate(Void... values) {
}
public interface onCheckedChanged {
public void getisupload(boolean issuccess);
}
public void setOnCheckedChanged(onCheckedChanged listener) {
this.listener = listener;
}
private static void showresult(String tishi) {
CommonTools.showShortToast(context, tishi);
}
}
4、上传图片到服务器的方法:
UploadUtils.uploadFile(file, requestURL + “?userId=” + userId);
public class UploadUtils {
private static final String TAG = "uploadFile";
private static final int TIME_OUT = 10 * 10000000; // 超时时间
private static final String CHARSET = "utf-8"; // 设置编码
public static final String SUCCESS = "1";
public static final String FAILURE = "0";
/**
* @android上传文件到服务器
*
* @param file
* 需要上传的文件
*
* @param RequestURL
* 请求的rul
*
* @return 返回响应的内容
*/
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();
String dd = conn.getResponseMessage();
Log.e(TAG, "response code:" + res);
if (res == 200) {
//-------------------------------读取响应内容
String sCurrentLine = "";
String sTotalString = "";
java.io.InputStream issss = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(issss));
while ((sCurrentLine = reader.readLine()) != null)
if (sCurrentLine.length() > 0)
sTotalString = sTotalString + sCurrentLine.trim();
Data.icon_user_pub = sTotalString.trim();
return SUCCESS;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return FAILURE;
}
}
5、服务器接受
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;
private ServletContext servletContext;
/**
* @see HttpServlet#HttpServlet()
*/
public FileImageUploadServlet() {
super();
}
/**
* 设置文件上传的初始化信息
*
*/
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("upload");
System.out.println("filedir=" + filedir);
servletContext = config.getServletContext();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 初始化相应流---------------------(1)
PrintWriter out = response.getWriter();
try {
// 获取输入流的数据------------------(2)
List<FileItem> items = this.upload.parseRequest(request);
if (items != null && !items.isEmpty()) {
// 循环读取文件流---------------------(3)
for (FileItem fileItem : items) {
String date = DateParse.date4String(new Date());
String filename = date + fileItem.getName();
String iconname = "/" + "upload" + "/" + filename;
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);
}
ServletContext application = (ServletContext) servletContext;
// 获取spring容器
WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(application);// 获取spring的context
// 获取userService的bean
UserService clientDao = (UserService) wac.getBean("userService");
int userId = Integer.parseInt(request.getParameter("userId"));
Tuser user = clientDao.getSingleUser(userId).get(0);
user.setHeaderImgUrl(iconname);
clientDao.modifyUser(user);
// 像前台输出json ------------------------------(3)
response.getWriter().write(iconname);
// 关闭流读取器----------------------------------(4)
fos.flush();
fos.close();
fis.close();
inputSteam.close();
System.out.println("文件:" + filename + "上传成功!");
}
}
System.out.println("上传文件成功!");
} catch (FileUploadException e) {
e.printStackTrace();
out.write("上传文件失败:" + e.getMessage());
}
}
}