当前位置:Gxlcms > html代码 > 文件上传_html/css_WEB-ITnose

文件上传_html/css_WEB-ITnose

时间:2021-07-01 10:21:17 帮助过:10人阅读

  相信有过Web开发经历的小朋友,对于文件上传都不陌生,但如何在自己的网站上提供文件上传呢?我想一定难到过很多同学,我就是其中的一个,近段时间因为开发的需要,总结了一下Web端文件上传的原理,在这里和大家分享一下。

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<4; i++)		{			buffer.append(random.nextInt(10));		}				return buffer.toString();	}		public static void main(String[] args) {		IPTimeStamp ipts = new IPTimeStamp("192.168.19.121");		System.out.println(ipts.getIPTimestamp());	}}

多文件上传:

SmartUpload smart = new SmartUpload();		smart.initialize(this.getServletConfig(),request,response);		try {			smart.upload();			for(int i=0; i
                        
                    

人气教程排行