该图片上传功能包括:
1.上传文件类型检查
2.上传文件大小控制
3.解决中文文件名乱码
引入的.jar文件:
commons-fileupload-1.2.1.jar
commons-io-1.2.jar
引入的.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;
}