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;
}
@Override
protected String doInBackground(String... strings) {
return uploadFile(file,strings[0]);
}
@Override
protected 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后台效果
=================
手机选择图片
![](https://img-blog.csdnimg.cn/20190226145826527.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L21laXhpX2FuZHJvaWQ=,size_16,color_FFFFFF,t_70)
java创建文件方法
![](https://img-blog.csdnimg.cn/20190226145927493.png)
### 上传成功!!
![](https://img-blog.csdnimg.cn/20190226150014141.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L21laXhpX2FuZHJvaWQ=,size_16,color_FFFFFF,t_70)
### 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();
}
}