java web图片上传和文件上传实例详解
javaweb图片上传和文件上传
图片上传和文件上传本质上是一样的,图片本身也是文件。文件上传就是将图片上传到服务器,方式虽然有很多,但底层的实现都是文件的读写操作。
注意事项
1.form表单一定要写属性enctype="multipart/form-data"
2.为了能保证文件能上传成功file控件的name属性值要和你提交的控制层变量名一致,
例如空间名是file那么你要在后台这样定义
privateFilefile;//file控件名
privateStringfileContentType;//图片类型
privateStringfileFileName;//文件名
1.jsp页面
<%@pagelanguage="java"contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <metahttp-equiv="Content-Type"content="text/html;charset=utf-8"> <metahttp-equiv="pragma"content="no-cache"/> <basetarget="_self"> <title>文件上传</title> </head> <body> <formmethod="post"action=""enctype="multipart/form-data"> <inputtype="file"name="file"value="file"> <inputtype="submit"value="确定"> </form> </body> </html>
1.页面数据需要提交的Controller
packagecom.cpsec.tang.chemical.action; importjava.io.File; importjava.io.IOException; importjava.util.Random; importjavax.annotation.Resource; importjavax.servlet.http.HttpServletRequest; importorg.apache.commons.io.FileUtils; importorg.apache.struts2.ServletActionContext; importorg.springframework.stereotype.Controller; importcom.cpsec.tang.chemical.biz.LunboBiz; importcom.cpsec.tang.chemical.entity.Image; importcom.opensymphony.xwork2.ActionSupport; @Controller("lunboAction") publicclassLunboActionextendsActionSupport{ /** * */ privatestaticfinallongserialVersionUID=1L; @Resource(name="lunboBiz") privateLunboBizlunboBiz; privateImageimage; privateFilefile;//file控件名 privateStringfileContentType;//图片类型 privateStringfileFileName;//文件名 privateIntegernumber; publicStringfindImage(){ image=lunboBiz.findImage(); returnSUCCESS; } publicStringalterImage(){ image=lunboBiz.findImage(); returnSUCCESS; } publicStringalterImage1(){ HttpServletRequestrequest=ServletActionContext.getRequest(); Stringroot=request.getRealPath("/upload");//图片要上传到的服务器路径 Stringnames[]=fileFileName.split("\\."); StringfileName=""; if(names.length>=1){ fileName=getRandomString(20)+"."+names[names.length-1]; } StringpicPath="upload/"+fileName;//图片保存到数据库的路径 Filefile1=newFile(root); try{ FileUtils.copyFile(file,newFile(file1,fileName)); } }catch(IOExceptione){ e.printStackTrace(); } returnSUCCESS; } /*获取一条随机字符串*/ publicStringgetRandomString(intlength){//length表示生成字符串的长度 Stringbase="abcdefghijklmnopqrstuvwxyz0123456789"; Randomrandom=newRandom(); StringBuffersb=newStringBuffer(); for(inti=0;i<length;i++){ intnumber=random.nextInt(base.length()); sb.append(base.charAt(number)); } returnsb.toString(); } }
这是通过复制的方式上传文件,还有其他方式
方法二
@Controller("contractAction") publicclassContractActionextendsActionSupport{ privatefinalstaticStringUPLOADDIR="/files";//文件上传的路径,在webContent下建立 privateFilefile;//input控件名一定为file //上传文件名集合 privateStringfileFileName; //上传文件内容类型集合 privateStringfileContentType; privateStringfilename; publicStringupload()throwsFileNotFoundException,IOException{ Stringpath=uploadFile();//文件保存数据库的路径 returnSUCCESS; } //执行上传功能 @SuppressWarnings("deprecation") publicStringuploadFile()throwsFileNotFoundException,IOException{ try{ InputStreamin=newFileInputStream(file); Stringdir=ServletActionContext.getRequest().getRealPath(UPLOADDIR); FilefileLocation=newFile(dir); //此处也可以在应用根目录手动建立目标上传目录 if(!fileLocation.exists()){ booleanisCreated=fileLocation.mkdir(); if(!isCreated){ //目标上传目录创建失败,可做其他处理,例如抛出自定义异常等,一般应该不会出现这种情况。 returnnull; } } //this.setFileFileName(getRandomString(20)); String[]Name=this.getFileFileName().split("\\."); StringfileName=getRandomString(20)+"."+Name[Name.length-1]; this.setFileFileName(fileName); System.out.println(fileName); FileuploadFile=newFile(dir,fileName); OutputStreamout=newFileOutputStream(uploadFile); byte[]buffer=newbyte[1024*1024]; intlength; while((length=in.read(buffer))>0){ out.write(buffer,0,length); } in.close(); out.close(); returnUPLOADDIR.substring(1)+"\\"+fileFileName; }catch(FileNotFoundExceptionex){ returnnull; }catch(IOExceptionex){ returnnull; } } publicstaticStringgetRandomString(intlength){ Stringstr="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; Randomrandom=newRandom(); StringBuffersb=newStringBuffer(); for(inti=0;i<length;i++){ intnumber=random.nextInt(62); sb.append(str.charAt(number)); } returnsb.toString(); } }
除了单图上传还有多图上传,原理都是一样的
packagecom.cpsec.tang.chemical.action; importjava.io.File; importjava.io.FileInputStream; importjava.io.FileNotFoundException; importjava.io.FileOutputStream; importjava.io.IOException; importjava.io.InputStream; importjava.io.OutputStream; importjava.util.List; importjavax.servlet.http.HttpServletRequest; importorg.apache.struts2.ServletActionContext; importcom.opensymphony.xwork2.ActionSupport; /** *多文件上传 */ publicclassFilesUploadActionextendsActionSupport{ //上传文件存放路径 privatefinalstaticStringUPLOADDIR="/upload"; //上传文件集合 privateList<File>file; //上传文件名集合 privateList<String>fileFileName; //上传文件内容类型集合 privateList<String>fileContentType; publicList<File>getFile(){ returnfile; } publicvoidsetFile(List<File>file){ this.file=file; } publicList<String>getFileFileName(){ returnfileFileName; } publicvoidsetFileFileName(List<String>fileFileName){ this.fileFileName=fileFileName; } publicList<String>getFileContentType(){ returnfileContentType; } publicvoidsetFileContentType(List<String>fileContentType){ this.fileContentType=fileContentType; } publicStringuploadform()throwsException{ HttpServletRequestrequest=ServletActionContext.getRequest(); Stringwebpath=null;//上传路径 for(inti=0;i<file.size();i++){ //循环上传每个文件 uploadFile(i); webpath="upload/"+this.getFileFileName().get(i); } return"SUCCESS"; } //执行上传功能 privateStringuploadFile(inti)throwsFileNotFoundException,IOException{ try{ InputStreamin=newFileInputStream(file.get(i)); Stringdir=ServletActionContext.getRequest().getRealPath(UPLOADDIR); FilefileLocation=newFile(dir); //此处也可以在应用根目录手动建立目标上传目录 if(!fileLocation.exists()){ booleanisCreated=fileLocation.mkdir(); if(!isCreated){ //目标上传目录创建失败,可做其他处理,例如抛出自定义异常等,一般应该不会出现这种情况。 returnnull; } } StringfileName=this.getFileFileName().get(i); FileuploadFile=newFile(dir,fileName); OutputStreamout=newFileOutputStream(uploadFile); byte[]buffer=newbyte[1024*1024]; intlength; while((length=in.read(buffer))>0){ out.write(buffer,0,length); } in.close(); out.close(); returnuploadFile.toString(); }catch(FileNotFoundExceptionex){ returnnull; }catch(IOExceptionex){ returnnull; } } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!