android上傳圖片到服務器,android的Activity和服務器那邊的完整代碼
服務器端servlet代碼:
public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
//獲取輸入流,是HTTP協議中的實體內容
ServletInputStream sis=request.getInputStream();
File file = new File(request.getSession().getServletContext().getRealPath
("/img/"),"img_"+0+".jpg");
for (int imgnum = 0;file.exists();imgnum++)
{
file = new File(request.getSession().getServletContext().getRealPath
("/img/"),"img_"+imgnum+".jpg");
}
//緩沖區
byte buffer[]=new byte[1024];
FileOutputStream fos=new FileOutputStream(file);
int len=sis.read(buffer, 0, 1024);
//把流里的信息循環讀入到文件中
while( len!=-1 )
{
fos.write(buffer, 0, len);
len=sis.readLine(buffer, 0, 1024);
}
fos.close();
sis.close();
}android客戶端代碼:
public static void uploadFile(String imageFilePath)
{
String actionUrl = "http://172.22.64.12:8080/UploadServer/ImageServlet";
try
{
URL url =new URL(actionUrl);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
DataOutputStream ds = new DataOutputStream(con.getOutputStream());
File file = new File(imageFilePath);
FileInputStream fStream = new FileInputStream(file);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
while((length = fStream.read(buffer)) != -1)
{
ds.write(buffer, 0, length);
}
fStream.close();
ds.flush();
InputStream is = con.getInputStream();
int ch;
StringBuffer b =new StringBuffer();
while( ( ch = is.read() ) != -1 )
{
b.append( (char)ch );
}
ds.close();
}
catch(Exception e)
{
e.printStackTrace();
}
} 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!