android上傳圖片至服務器
本實例實現了android上傳手機圖片至服務器,服務器進行保存
複製代碼
- 服務器servlet代碼
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
-
- String temp=request.getSession().getServletContext().getRealPath("/")+"temp"; //臨時目錄
- System.out.println("temp="+temp);
- String loadpath=request.getSession().getServletContext().getRealPath("/")+"Image"; //上傳文件存放目錄
- System.out.println("loadpath="+loadpath);
- DiskFileUpload fu = new DiskFileUpload();
- fu.setSizeMax(1*1024*1024); // 設置容許用戶上傳文件大小,單位:字節
- fu.setSizeThreshold(4096); // 設置最多隻容許在內存中存儲的數據,單位:字節
- fu.setRepositoryPath(temp); // 設置一旦文件大小超過getSizeThreshold()的值時數據存放在硬盤的目錄
-
- //開始讀取上傳信息
- int index=0;
- List fileItems = null;
-
-
- try {
- fileItems = fu.parseRequest(request);
- System.out.println("fileItems="+fileItems);
- } catch (Exception e) {
- e.printStackTrace();
- }
-
-
- Iterator iter = fileItems.iterator(); // 依次處理每一個上傳的文件
- while (iter.hasNext())
- {
- FileItem item = (FileItem)iter.next();// 忽略其餘不是文件域的全部表單信息
- if (!item.isFormField())
- {
- String name = item.getName();//獲取上傳文件名,包括路徑
- name=name.substring(name.lastIndexOf("\\")+1);//從全路徑中提取文件名
- long size = item.getSize();
- if((name==null||name.equals("")) && size==0)
- continue;
- int point = name.indexOf(".");
- name=(new Date()).getTime()+name.substring(point,name.length())+index;
- index++;
- File fNew= new File(loadpath, name);
- try {
- item.write(fNew);
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
-
- }
- else //取出不是文件域的全部表單信息
- {
- String fieldvalue = item.getString();
- //若是包含中文應寫爲:(轉爲UTF-8編碼)
- //String fieldvalue = new String(item.getString().getBytes(),"UTF-8");
- }
- }
- String text1="11";
- response.sendRedirect("result.jsp?text1=" + text1);
- }
複製代碼
android客戶端代碼
複製代碼
- public class PhotoUpload extends Activity {
- private String newName = "image.jpg";
- private String uploadFile = "/sdcard/image.JPG";
- private String actionUrl = "http://192.168.0.71:8086/HelloWord/myForm";
- private TextView mText1;
- private TextView mText2;
- private Button mButton;
- @Override
- public void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.photo_upload);
- mText1 = (TextView) findViewById(R.id.myText2);
- //"文件路徑:\n"+
- mText1.setText(uploadFile);
- mText2 = (TextView) findViewById(R.id.myText3);
- //"上傳網址:\n"+
- mText2.setText(actionUrl);
-
- mButton = (Button) findViewById(R.id.myButton);
- mButton.setOnClickListener(new View.OnClickListener()
- {
- public void onClick(View v)
- {
- uploadFile();
- }
- });
- }
-
- private void uploadFile()
- {
- String end = "\r\n";
- String twoHyphens = "--";
- String boundary = "*****";
- try
- {
- URL url =new URL(actionUrl);
- HttpURLConnection con=(HttpURLConnection)url.openConnection();
-
- con.setDoInput(true);
- con.setDoOutput(true);
- con.setUseCaches(false);
-
- con.setRequestMethod("POST");
-
- con.setRequestProperty("Connection", "Keep-Alive");
- con.setRequestProperty("Charset", "UTF-8");
- con.setRequestProperty("Content-Type",
- "multipart/form-data;boundary="+boundary);
-
- DataOutputStream ds =
- new DataOutputStream(con.getOutputStream());
- ds.writeBytes(twoHyphens + boundary + end);
- ds.writeBytes("Content-Disposition: form-data; " +
- "name=\"file1\";filename=\"" +
- newName +"\"" + end);
- ds.writeBytes(end);
-
- FileInputStream fStream = new FileInputStream(uploadFile);
-
- int bufferSize = 1024;
- byte[] buffer = new byte[bufferSize];
- int length = -1;
-
- while((length = fStream.read(buffer)) != -1)
- {
-
- ds.write(buffer, 0, length);
- }
- ds.writeBytes(end);
- ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
-
- fStream.close();
- ds.flush();
-
- InputStream is = con.getInputStream();
- int ch;
- StringBuffer b =new StringBuffer();
- while( ( ch = is.read() ) != -1 )
- {
- b.append( (char)ch );
- }
-
- showDialog("上傳成功"+b.toString().trim());
-
- ds.close();
- }
- catch(Exception e)
- {
- showDialog("上傳失敗"+e);
- }
- }
-
- private void showDialog(String mess)
- {
- new AlertDialog.Builder(PhotoUpload.this).setTitle("Message")
- .setMessage(mess)
- .setNegativeButton("肯定",new DialogInterface.OnClickListener()
- {
- public void onClick(DialogInterface dialog, int which)
- {
- }
- })
- .show();
- }
- }
歡迎關注本站公眾號,獲取更多信息