本文记录的是我写的一个用struts 1.3实现的文件上传和下载的例子
由于各种文件都可能被上传或者下载,所以输入流使用字节流而不是字符流。字符流只用于文本文件。
①建立web工程,引入struts开发包
②写register.jsp(有文件传输,表单提交只能用post)
如果我们的表单有文件这样的控件,则需要重新指定表单的编码方式
<form enctype="multipart/form-data" action="/strutsfileupanddown/register.do" method="post"> 名字:<input type="text" name="name"><br/> 头像:<input type="file" name="myphoto"><br/> <input type="submit" value="提交" /> </form>
④在ActionForm中,对应表单中file的属性为FormFile数据类型
⑤牵线,写业务逻辑
文件上传核心代码:
InputStream is = null; OutputStream os = null; try { //取出输入流 is = formFile.getInputStream(); //得到输出流 -> 文件 //1. 得到file文件夹的上传到tomcat服务器后的绝对路径 String keepFilePath = this.getServlet().getServletContext().getRealPath("/file"); System.out.println("keepFilePath="+keepFilePath); os = new FileOutputStream(keepFilePath+"\\"+fileName); //读取文件并写到服务器file int len = 0; //做一个缓存buffer byte [] bytes = new byte[1024]; //循环处理 while((len=is.read(bytes))>0){ //读一点,写一点 os.write(bytes, 0, len); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ try { is.close(); os.close(); } catch (Exception e2) { // TODO: handle exception }
1. 中文名字的文件
使用过滤器,解决中文乱码问题
2. 文件覆盖问题
利用UUID类产生伪随机数作为文件名
public static String getNewFileName(String fileName){ int beginIndex = fileName.lastIndexOf("."); String newFileName = UUID.randomUUID().toString() + fileName.substring(beginIndex, fileName.length()); return newFileName; }
//获取用户名 String username = request.getParameter("user"); //获取Register对象 RegisterService rs = new RegisterService(); Register r = rs.getRegister(username); response.setContentType("text/html;charset=utf-8"); //如果文件名有中文,需要对其进行URL编码 String filterFilename = ""; try { filterFilename = URLEncoder.encode(r.getPhotoNameOld(),"utf-8"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //设置一个头,告诉浏览器有文件要下载 response.setHeader("Content-Disposition", "attachment; filename="+filterFilename); //下载文件 //1.先获取要下载文件的绝对路径 String filePath = this.getServlet().getServletContext().getRealPath("/file"); //文件全路径 String fileAllPath = filePath + "\\" + r.getPhoteNameNew(); FileInputStream fis = null; OutputStream os = null; //定义缓存 byte [] buffer = new byte[1024]; int len = 0; try { fis = new FileInputStream(fileAllPath); os = response.getOutputStream(); while((len = fis.read(buffer))>0){ os.write(buffer, 0, len); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ try { os.close(); fis.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } return null; }
在下载的页面,应该这样写:
<tr><td>${user.username }</td> <td><img width="50px" src="/strutsfileupanddown/file/${user.photeNameNew}"></td> <td>${user.photoNameOld }</td> <td><a href="/strutsfileupanddown/downLoadFile.do?user=${user.username }">下载</a></td></tr>