1、完整上传图片代码方法:
private static final int TIME_OUT = 10*1000; //超时时间
private static final String CHARSET = "utf-8"; //设置编码
/*** android上传文件到服务器* @param file 需要上传的文件* @param RequestURL 请求的rul* @return 返回响应的内容*/public static String uploadFile(File file, String RequestURL){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.setRequestProperty("filename",file.getName());//添加头部参数,只有这个key 才可以得到对应的文件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);conn.setRequestProperty("action", "upload");conn.connect();Log.e("lgq", "re==uploadFile=====" + file.getPath()+"......."+file.getName());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是文件的名字,包含后缀名的 比如: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();if(res==200){InputStream input = conn.getInputStream();
// StringBuffer sb1= new StringBuffer();int ss ;byte[] buffer = new byte[1024];StringBuilder builder =new StringBuilder();while((ss=input.read(buffer))!=-1){
// sb1.append((char)ss);builder.append(new String(buffer, 0, ss, "UTF-8"));}result = builder.toString();System.out.println(result);}}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return result;}
2、异步请求方法
public class Upload extends AsyncTask<String,Void,String> {File file;public Upload(File file){this.file = file;}@Overrideprotected String doInBackground(String... strings) {return uploadFile(file,strings[0]);}@Overrideprotected void onPostExecute(String s) {super.onPostExecute(s);Log.i("lgq", "re==onPostExecute=====" + s);if(s.contains("succedd")){Toast.makeText(getBaseContext(),"上传成功",Toast.LENGTH_SHORT).show();}else{Toast.makeText(getBaseContext(),"上传失败",Toast.LENGTH_SHORT).show();}}
}
3、选中图片,开始上传图片
String firestrUrl = "http://192.168.0.110:8080/servletDemo/testa?method=lgqservice";
private File compressedImage1File;
new Upload(compressedImage1File).execute(firestrUrl);
4、手机上传图片到java后台效果
手机选择图片
java创建文件方法
上传成功!!
demo链接:https://download.csdn.net/download/meixi_android/10976495
https://download.csdn.net/download/meixi_android/11006216
在线回复bug:QQ1085220040
附java HttpServlet 上传图片主要方法完整代码实例:
public void lgqservice(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String filename = request.getHeader("filename");
System.out.println("===service进来了====="+ filename);
List<String> msgList2 = new ArrayList<String>();
if (request.getContentLength() > 0) {
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = request.getInputStream();
// 给新文件拼上时间毫秒,防止重名
long now = System.currentTimeMillis();
File file = new File("d:/", "file-" + now + ".png");
file.createNewFile();
outputStream = new FileOutputStream(file);
byte temp[] = new byte[1024];
int size = -1;
while ((size = inputStream.read(temp)) != -1) { // 每次读取1KB,直至读完
outputStream.write(temp, 0, size);
}
msgList2.add("succedd成功" );
okreString = "上传成功";
} catch (IOException e) {
msgList2.add("defeated失败" );
okreString = "上传失败";
} finally {
outputStream.close();
inputStream.close();
}
}
JSONObject result = new JSONObject();
result.put("success", true);
result.put("okstatus",okreString );
System.out.println("FileLoadServlet=====8888==="+result);
response.getWriter().print(result);
// response.getWriter().print(formatJsonData("msg", msgList2));
}