JavaWeb file upload and download

Use SmartUpload plugin:
Required file package: smartupload.jar

JSP:

<form action="./smartupload" method="post" enctype="multipart/form-data">
姓名:<input type="text" name="username"><br>
照片1:<input type="file" name="picFile"><br>
<!-- 照片2:<input type="file" name="pic2"><br>
照片3:<input type="file" name="pic3"><br> -->
<input type="submit" value="上传">
<input type="reset" value="重置">
//</form>

Servlet:

request.setCharacterEncoding("utf-8") ; //设置编码格式
SmartUpload smart = new SmartUpload() ; //初始化组件
smart.initialize(this.getServletConfig(), request,response) ; // 初始化上传操作
try {
smart.upload() ;
} catch (SmartUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // 上传准备
String name = smart.getRequest().getParameter("uname") ; //获取普通表单的内容
IPTimeStamp its = new IPTimeStamp(request.getRemoteAddr()) ; // IPTimeStamp是自己定义的工具,取得客户端的IP地址,用于生产保存后的文件名
for(int x=0;x
String ext = smart.getFiles().getFile(x).getFileExt() ; // 文件扩展名称
String fileName = its.getIPTimeRand() + "." + ext ;
try {
System.out.println(request.getSession().getServletContext().getRealPath("/")+"upload"+java.io.File.separator + fileName); //文件储存的路径 
smart.getFiles().getFile(x).saveAs(request.getSession().getServletContext().getRealPath("/")+"upload"+java.io.File.separator + fileName) ;
} catch (SmartUploadException e) {
e.printStackTrace();
}
}

Tool class: use ip address + date + three random numbers to generate a string of numbers as the saved file name

package Util;
import java.text.SimpleDateFormat ;
import java.util.Date ;
import java.util.Random ;
public class IPTimeStamp {
private SimpleDateFormat sdf = null ;
private String ip = null ;
public IPTimeStamp(){
}
public IPTimeStamp(String ip){
this.ip = ip ;
}
public String getIPTimeRand(){
StringBuffer buf = new StringBuffer() ;
if(this.ip != null){
String s[] = this.ip.split("\\.") ;
for(int i=0;i
buf.append(this.addZero(s[i],3)) ;
}
}
buf.append(this.getTimeStamp()) ;
Random r = new Random() ;
for(int i=0;i<3;i++){
buf.append(r.nextInt(10)) ;
}
return buf.toString() ;
}
public String getDate(){
this.sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") ;
return this.sdf.format(new Date()) ;
}
public String getTimeStamp(){
this.sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS") ;
return this.sdf.format(new Date()) ;
}
private String addZero(String str,int len){
StringBuffer s = new StringBuffer() ;
s.append(str) ;
while(s.length() < len){
s.insert(0,"0") ;
}
return s.toString() ;
}
public static void main(String args[]){
System.out.println(new IPTimeStamp("192.168.1.1").getIPTimeRand()) ;
}
}

Full project download: http://download-vdisk.sina.com.cn/22563125/6e9d9fdd364911e5c7bdf0dd8c484b396e7d658c?ssig=q90iprzDKZ&Expires=1384967068&KID=sae,l30zoo1wmz&fn=FileUpDowmDemo.war

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325988484&siteId=291194637