Java Struts(檔案下載),javastruts
1.從註冊成功頁面跳轉至使用者詳情頁面(跳轉至UserListAction)
2.UserListAction調用service獲得使用者列表,並將這些資料傳送到UserList.jsp中,UserList.jsp將這些資料進行展示
public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) {UsersService service=new UsersService();ArrayList<Users> userList = service.getUserList();request.setAttribute("userList", userList);return mapping.findForward("showuser");}
public ArrayList<Users> getUserList(){String sql="select * from _users";List<Object[]> al = SqlHelper.executeQuery(sql, null);ArrayList<Users> userList=new ArrayList<Users>();Users user=new Users();for(Object[] obj:al){user.setUsername((String) obj[0]);user.setPhoto((String) obj[1]);user.setPhoto2((String) obj[2]);userList.add(user);}return userList;}
<h1>使用者列表</h1> <c:forEach items="${userList}" var="user"> ${user.username} <img src="/StrutsFileUpAndDown/file/${user.photo}" width=50px/><a href="/StrutsFileUpAndDown/downloadFile.do?filename=${user.username}">點擊下載</a><br/> </c:forEach>
3.在UserList中存在一個跳轉標籤,這個標籤可以進行下載帳戶圖片,當點擊這個頁面後,跳轉至DownloadFileAction,這個Action進行下載操作
public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) {FileInputStream fis=null;OutputStream os=null;String fileName = request.getParameter("filename");UsersService usersService=new UsersService();Users user = usersService.getUser(fileName);//下載檔案//1.先擷取到下載檔案的絕對路徑String filePath = this.getServlet().getServletContext().getRealPath("/file");String userPhoto = user.getPhoto();response.setContentType("text/html;charset=utf-8");//如果檔案具有中文,則需要進行Url編碼//設定一個頭,告訴瀏覽器有檔案要下載try {response.setHeader("Content-Disposition","attachement; filename="+java.net.URLEncoder.encode(userPhoto,"utf-8"));} catch (UnsupportedEncodingException e1) {e1.printStackTrace();}String fileAllPath=filePath+"\\"+userPhoto;byte []buff=new byte[1024];int len=0;try {fis=new FileInputStream(fileAllPath);os=response.getOutputStream();while((len=fis.read(buff))!=-1){os.write(buff,0,len);}} catch (Exception e) {e.printStackTrace();}finally{try {fis.close();os.close();} catch (IOException e) {e.printStackTrace();}}return mapping.findForward("goback");}
public Users getUser(String username){String sql="select * from _users where username=?";String[] parameter={username};ArrayList<Object[]> al = SqlHelper.executeQuery(sql, parameter);Object[] objects = al.get(0);Users user=new Users();user.setUsername((String) objects[0]);user.setPhoto((String) objects[1]);user.setPhoto2((String) objects[2]);return user;}
1).先擷取上個頁面傳輸過來的使用者名稱,然後再根據這個使用者名稱從資料庫中擷取這個使用者的相關資料。
2).擷取下載檔案的絕對路徑,response設定編碼格式和頭;如果檔案具有中文,則需要進行url編碼
3).建立一個輸入資料流,用於讀取檔案;從response中擷取一個輸出資料流,用於輸出
4).通過輸入輸出資料流,將檔案進行輸出