为了解决图片上传问题,在网上搜了一些资料,某些源码真的不敢恭维,浪费了很多时间和精力,最后还是经过各种尝试写出来了。分享一下,尽量帮大家节省时间和精力。
android端源码:
private void uploadFile(){
try {
URL url = new URL("http://127.0.0.1:8082/jobserver/app/IamgeUpload_Upload.action?fileName=image.jpg");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","text/html");
conn.setRequestProperty("Cache-Control","no-cache");
conn.setRequestProperty("Charsert", "UTF-8");
conn.connect();
conn.setConnectTimeout(10000);
OutputStream out =conn.getOutputStream();
//获得要上传的文件
File file = new File("/sdcard/image.jpg");
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] buffer = new byte[1024];
while ((bytes = in.read(buffer)) != -1) {
out.write(buffer, 0, bytes);
}
in.close();
out.flush();
out.close();
conn.getInputStream();
conn.disconnect();
} catch (Exception e) {
System.out.println("上传文件出现异常!" + e);
e.printStackTrace();
}
}
struts2 服务器端:
public String Upload(){
HttpServletRequest request = ServletActionContext.getRequest();
String fileName = request.getParameter("fileName");
InputStream inputS = null;
try {
inputS = request.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
File file = new File("F:\\upload");
//如果文件夹不存在,创建文件夹
if(!file.exists()){
file.mkdirs();
}
FileOutputStream fileOS = null;
try {
fileOS = new FileOutputStream("F:\\upload\\"+fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int size = 0;
byte[] buffer = new byte[1024];
try {
while ((size = inputS.read(buffer,0,1024)) != -1) {
fileOS .write(buffer, 0, size);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
fileOS .close();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputS .close();
} catch (IOException e) {
e.printStackTrace();
}
return Action.NONE;
}