commons-fileupload 图片上传示例

该图片上传功能包括: 
    1.上传文件类型检查 
    2.上传文件大小控制 
    3.解决中文文件名乱码 

引入的.jar文件: 
   commons-fileupload-1.2.1.jar 
   commons-io-1.2.jar 

JSP页面:
function form_submit(){
var img=document.getElementByIdx_x("bg_img").value;
if(img==""){
alert("请选择文件");
return false;
}
var rex=/(\.jpg|\.gif|\.png)$/i;
if(!rex.test(img)){
alert("文件类型错误");
return false;
}
}




后台处理类:

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;

public String upload() throws Exception { 
String realPath = session.getServletContext().getRealPath("/");  
       
String uploadPath = "/upload/";  
        String tempPath = "/upload/temp/";  
         
        DiskFileUpload fu = new DiskFileUpload();
        fu.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB  
        fu.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb  
        fu.setRepositoryPath(realPath+tempPath); // 设置临时目录  
        fu.setHeaderEncoding("UTF-8");//设置字符集 防止中文文件名乱码  
        
        List fileItems = fu.parseRequest(request); //得到提交的数据        
        Iterator i = fileItems.iterator();
        
        ResJson resJson = new ResJson(false, "LOGO上传失败!");
                        
        String allowExts = ".jpg.jpeg.gif.png";  
        
        String newname = getnumber();
        
        FileItem imgFile = null;
     try{  
       while(i.hasNext()) {
           FileItem fi = (FileItem)i.next();
           String fileName = fi.getName();// 获得文件名,其中包括用户提交的路径即html file的value  
           if(fileName != null) {
               String fileExt = fileName.substring(fileName.lastIndexOf("."));
               
               if(allowExts.indexOf(fileExt.toLowerCase())==-1){
                   resJson.setSuccess(false);
        resJson.setMsg("LOGO上传失败!此文件类型不允许上传,请重新选择后缀为“.jpg 或 .jpeg 或 .gif 或 .png”的文件后上传!");
               }else if(fi.getFieldName().equals("bg_img")){ //多文件的话判断html file的name  
                   imgFile=fi;  
               }
           }
       }
       
       if(imgFile!=null){
           String imgFileName = imgFile.getName();  
           imgFileName = imgFileName.substring(imgFileName.lastIndexOf("\")+1);  
                       
newname = newname + imgFileName.substring(imgFileName.length() - 4,imgFileName.length());
           
           File fImg = new File(realPath + uploadPath + newname);
                       
           System.out.println("imgFileName="+imgFileName+"  fImg="+fImg+"  newname="+newname);
           if(fImg.exists()){
               resJson.setSuccess(false);
        resJson.setMsg("LOGO上传失败!此文件类型不允许上传!");
           }else{  
               imgFile.write(fImg);
               resJson.setSuccess(true);
        resJson.setMsg("LOGO上传成功!");
        resJson.setContent("upload/" + newname);
           }
       }
   }catch(FileUploadBase.SizeLimitExceededException e){
       resJson.setSuccess(false);
resJson.setMsg("LOGO上传失败!文件大小超出,最大上传限制4M");
   }
   out.append(JSON.toJSONString(resJson));
return NULL;
}

public String getnumber() {
String ;
//获取随机
Random r = new Random(); 
String str = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
for(int i=0; i<30; i++) {
int num = r.nextInt(str.length()); 
char c = str.charAt(num); 
autoid = autoid + c;
}
return autoid;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值