jsp页面的主要代码:
单文件上传
文件重命名
自动生成文件名
多文件上传
下面是具体的上传方法介绍
单文件上传:
SmartUpload smart = new SmartUpload(); smart.initialize(this.getServletConfig(),request,response); try { smart.upload(); smart.save("images"); } catch (SmartUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); }
文件重命名:
SmartUpload smart = new SmartUpload(); smart.initialize(this.getServletConfig(),request,response); try { smart.upload(); String imgname = smart.getRequest().getParameter("imgname"); String absPath = this.getServletContext().getRealPath("/images");//获取文件的保存路径 System.out.println(absPath); String ext = smart.getFiles().getFile(0).getFileExt();//获取文件的后缀名 String fileName = absPath+File.separator+imgname+"."+ext;//生成文件的保存名 System.out.println("File name="+fileName); smart.getFiles().getFile(0).saveAs(fileName); } catch (SmartUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); }
自动生成文件名:
SmartUpload smart = new SmartUpload(); smart.initialize(this.getServletConfig(),request,response); String disFile = ""; try { smart.upload(); //String imgname = smart.getRequest().getParameter("imgname"); IPTimeStamp ipts = new IPTimeStamp(); String imgname = ipts.getIPTimestamp(); String absPath = this.getServletContext().getRealPath("/images"); System.out.println(absPath); String ext = smart.getFiles().getFile(0).getFileExt(); String fileName = absPath+File.separator+imgname+"."+ext; System.out.println("File name="+fileName); smart.getFiles().getFile(0).saveAs(fileName); disFile = imgname+"."+ext; } catch (SmartUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); }
生成随机文件名的代码:
package cn.edu.hpu.util;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Random;public class IPTimeStamp { private String ip; public IPTimeStamp() { } public IPTimeStamp(String ip) { this.ip = ip; } public String getIPTimestamp() { StringBuffer buffer = new StringBuffer(); if(ip != null) { String [] digits = ip.split("\\."); for(String s : digits) { buffer.append(s); } } //时间 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String time = sdf.format(new Date()); buffer.append(time); Random random = new Random(); for(int i=0; i
多文件上传:
SmartUpload smart = new SmartUpload(); smart.initialize(this.getServletConfig(),request,response); try { smart.upload(); for(int i=0; i
相信看到这里,大家一定已经明白如何完成文件上传了。(如有错误还望指正。谢谢)
查看更多关于文件上传_html/css_WEB-ITnose的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did105993