一:上传
1:在jsp页面的form表单中一定要加(ENCTYPE="multipart/form-data"),并且方法为post!
2:servlet
response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); SmartUpload mySmartUpload = new SmartUpload(); try { //1:初始化,有两种方式 //initialize(pageContext) //initialize(servletConfig,request,response); mySmartUpload.initialize(config,request,response); //2:准备上传 mySmartUpload.upload(); // 上传文件个数 com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0); //3:上传 myFile.saveAs("/" + myFile.getFileName()); out.print("上传成功"); } catch (Exception e) { out.println("Error : " + e.toString()); }
一些扩展方法
//设置单个文件大小 mySmartUpload.setMaxFileSize(100000); //设置总的上传文件大小 mySmartUpload.setTotalMaxFileSize(20000); //设置允许上传的文件格式 mySmartUpload.setAllowedFilesList("jpg,gif,png"); //获取单个文件 File file=su.getFiles().getFile(0); (Files对象保存了上传的所有文件)
我们可以通过下面的方法得到config
private ServletConfig config; final public void init(ServletConfig config) throws ServletException { this.config = config; }
这里是得到pageContext
PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, request, response, null, true,8192, true);
二:下载
SmartUpload su = new SmartUpload(); su.initialize(pageContext); // 设定contentDisposition为null以禁止浏览器自动打开文件, //保证点击链接后是下载文件。若不设定,则下载的文件扩展名为 //doc时,浏览器将自动用word打开它。扩展名为pdf时, //浏览器将用acrobat打开。 su.setContentDisposition(null); //开始下载 su.downloadFile("xml\\"+filename);
三:下载、上传中文乱码问题
这个问题有高人给出了解决方案
/*jspSmartUpload虽然能下载文件,但对中文支持不足。若下载的文件名中有汉字,则浏览器在提示另存的文件名时,显示的是一堆乱码,很扫人兴。上面的例子就是这样。(这个问题也是众多下载组件所存在的问题,很少有人解决,搜索不到相关资料,可叹!) 为了给jspSmartUpload组件增加下载中文文件的支持,我对该组件进行了研究,发现对返回给浏览器的另存文件名进行UTF-8编码后,浏览器便能正确显示中文名字了。这是一个令人高兴的发现。于是我对jspSmartUpload组件的SmartUpload类做了升级处理,增加了toUtf8String这个方法,改动部分源码如下:*/ public void downloadFile(String s, String s1, String s2, int i) throws ServletException, IOException, SmartUploadException { if(s == null) throw new IllegalArgumentException("File '" + s + "' not found (1040)."); if(s.equals("")) throw new IllegalArgumentException("File '" + s + "' not found (1040)."); if(!isVirtual(s) && m_denyPhysicalPath) throw new SecurityException("Physical path is denied (1035)."); if(isVirtual(s)) s = m_application.getRealPath(s); java.io.File file = new java.io.File(s); FileInputStream fileinputstream = new FileInputStream(file); long l = file.length(); boolean flag = false; int k = 0; byte abyte0[] = new byte[i]; if(s1 == null) m_response.setContentType("application/x-msdownload"); else if(s1.length() == 0) m_response.setContentType("application/x-msdownload"); else m_response.setContentType(s1); m_response.setContentLength((int)l); m_contentDisposition = m_contentDisposition != null ? m_contentDisposition : "attachment;"; if(s2 == null) m_response.setHeader("Content-Disposition", m_contentDisposition + " filename=" + toUtf8String(getFileName(s))); else if(s2.length() == 0) m_response.setHeader("Content-Disposition", m_contentDisposition); else m_response.setHeader("Content-Disposition", m_contentDisposition + " filename=" + toUtf8String(s2)); while((long)k < l) { int j = fileinputstream.read(abyte0, 0, i); k += j; m_response.getOutputStream().write(abyte0, 0, j); } fileinputstream.close(); } /** * 将文件名中的汉字转为UTF8编码的串,以便下载时能正确显示另存的文件名. * 纵横软件制作中心雨亦奇2003.08.01 * @param s 原文件名 * @return 重新编码后的文件名 */ public static String toUtf8String(String s) { StringBuffer sb = new StringBuffer(); for (int i=0;i<s.length();i++) { char c = s.charAt(i); if (c >= 0 && c <= 255) { sb.append(c); } else { byte[] b; try { b = Character.toString(c).getBytes("utf-8"); } catch (Exception ex) { System.out.println(ex); b = new byte[0]; } for (int j = 0; j < b.length; j++) { int k = b[j]; if (k < 0) k += 256; sb.append("%" + Integer.toHexString(k). toUpperCase()); } } } return sb.toString(); }
四:下面是个牛人给的例子,据说能解决所有上传、下载过程中的乱码问题
上传:
upload.jsp
<%@ page contentType="text/html; charset=gb2312" %> <% request.setCharacterEncoding("gb2312"); // 这句话很重要,否则遇到中文就出错~ %> <HTML> <HEAD><TITLE>上传</TITLE> <META content="text/html; charset=gb2312" http-equiv=Content-Type> </HEAD> <BODY leftMargin=0 topMargin=0> <FORM action="upload_ok.jsp" method=post name="Upload" enctype="multipart/form-data"> <input type="file" name="file" > </FORM> </td> </tr> </table> </BODY></HTML>
upload_ok.jsp
<%@ page contentType="text/html;charset=gb2312" %> <%@ page import="com.jspsmart.upload.*" %> <HTML><HEAD><TITLE>上传成功!</TITLE> <META content="text/html; charset=gb2312" http-equiv=Content-Type> </HEAD> <BODY leftMargin=0 topMargin=0> <jsp:useBean id="mySmartUpload" scope="page" class="com.jspsmart.upload.SmartUpload" /> <table width="80%" border="0" cellpadding="0" cellspacing="0" bgcolor="#DEE7EF"> <tr> <td align="center"> <% int count=0; String fileName = null; mySmartUpload.initialize(pageContext); mySmartUpload.upload(); com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0); if (!myFile.isMissing()) { //String ext=myFile.getFileExt();//得到后缀 fileName = myFile.getFileName(); myFile.saveAs("/files/" + fileName);//你要存放文件所在文件夹的相对路径 out.println("文件:<b>"+fileName+"</b>上传成功!<br>文件大小:" + myFile.getSize() + "kb<BR>"); } %> </BODY></HTML>
下载:
文件的超连接写法范例: <% String fname ="中文测试.xsl"; //假设你的文件名是:中文测试.xsl %> <A target="_blank" href="Download.jsp?filename=<%=fname%>">下 载</A> 文件的超连接写法范例-2 重新用utf-8对文件名编码: <%@ page contentType="text/html;charset=gb2312" session="true"%> <% String name=java.net.URLEncoder.encode("世界文化.doc","UTF-8");%> <a href="c:\<%=name%>">世界文化.doc</a>
Download.jsp
<% java.io.BufferedInputStream bis=null; java.io.BufferedOutputStream bos=null; try{ String filename=request.getParameter("filename"); filename=new String(filename.getBytes("iso8859-1"),"gb2312"); response.setContentType("application/x-msdownload"); response.setHeader("Content-disposition","attachment; filename="+new String(filename.getBytes("gb2312"),"iso8859-1")); bis =new java.io.BufferedInputStream(new java.io.FileInputStream(config.getServletContext().getRealPath("files/" + filename))); bos=new java.io.BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff,0,bytesRead); } } catch(Exception e){ e.printStackTrace(); } finally { if (bis != null)bis.close(); if (bos != null)bos.close(); } %>