java web图片上传和文件上传实例详解
程序员文章站
2024-03-09 18:05:59
java web图片上传和文件上传
图片上传和文件上传本质上是一样的,图片本身也是文件。文件上传就是将图片上传到服务器,方式虽然有很多,但底层的实现都是文件的读写操作。...
java web图片上传和文件上传
图片上传和文件上传本质上是一样的,图片本身也是文件。文件上传就是将图片上传到服务器,方式虽然有很多,但底层的实现都是文件的读写操作。
注意事项
1.form表单一定要写属性enctype="multipart/form-data"
2.为了能保证文件能上传成功file控件的name属性值要和你提交的控制层变量名一致,
例如空间名是file那么你要在后台这样定义
private file file; //file控件名
private string filecontenttype;//图片类型
private string filefilename; //文件名
1.jsp页面
<%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%> <!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="pragma" content="no-cache" /> <base target="_self"> <title>文件上传</title> </head> <body> <form method="post" action="" enctype="multipart/form-data"> <input type="file" name="file" value="file"> <input type="submit" value="确定"> </form> </body> </html>
1.页面数据需要提交的controller
package com.cpsec.tang.chemical.action; import java.io.file; import java.io.ioexception; import java.util.random; import javax.annotation.resource; import javax.servlet.http.httpservletrequest; import org.apache.commons.io.fileutils; import org.apache.struts2.servletactioncontext; import org.springframework.stereotype.controller; import com.cpsec.tang.chemical.biz.lunbobiz; import com.cpsec.tang.chemical.entity.image; import com.opensymphony.xwork2.actionsupport; @controller("lunboaction") public class lunboaction extends actionsupport { /** * */ private static final long serialversionuid = 1l; @resource(name="lunbobiz") private lunbobiz lunbobiz; private image image; private file file; //file控件名 private string filecontenttype;//图片类型 private string filefilename; //文件名 private integer number; public string findimage(){ image=lunbobiz.findimage(); return success; } public string alterimage(){ image=lunbobiz.findimage(); return success; } public string alterimage1(){ httpservletrequest request = servletactioncontext.getrequest(); string root = request.getrealpath("/upload");//图片要上传到的服务器路径 string names[]=filefilename.split("\\."); string filename=""; if(names.length>=1){ filename=getrandomstring(20)+"."+names[names.length-1]; } string picpath="upload/"+filename;//图片保存到数据库的路径 file file1=new file(root); try { fileutils.copyfile(file, new file(file1,filename)); } } catch (ioexception e) { e.printstacktrace(); } return success; } /*获取一条随机字符串*/ public string getrandomstring(int length) { //length表示生成字符串的长度 string base = "abcdefghijklmnopqrstuvwxyz0123456789"; random random = new random(); stringbuffer sb = new stringbuffer(); for (int i = 0; i < length; i++) { int number = random.nextint(base.length()); sb.append(base.charat(number)); } return sb.tostring(); } }
这是通过复制的方式上传文件,还有其他方式
方法二
@controller("contractaction") public class contractaction extends actionsupport { private final static string uploaddir = "/files";//文件上传的路径,在webcontent下建立 private file file; //input控件名一定为file //上传文件名集合 private string filefilename; //上传文件内容类型集合 private string filecontenttype; private string filename; public string upload() throws filenotfoundexception, ioexception{ string path=uploadfile();//文件保存数据库的路径 return success; } //执行上传功能 @suppresswarnings("deprecation") public string uploadfile() throws filenotfoundexception, ioexception { try { inputstream in = new fileinputstream(file); string dir = servletactioncontext.getrequest().getrealpath(uploaddir); file filelocation = new file(dir); //此处也可以在应用根目录手动建立目标上传目录 if(!filelocation.exists()){ boolean iscreated = filelocation.mkdir(); if(!iscreated) { //目标上传目录创建失败,可做其他处理,例如抛出自定义异常等,一般应该不会出现这种情况。 return null; } } // this.setfilefilename(getrandomstring(20)); string[] name=this.getfilefilename().split("\\."); string filename=getrandomstring(20)+"."+name[name.length-1]; this.setfilefilename(filename); system.out.println(filename); file uploadfile = new file(dir, filename); outputstream out = new fileoutputstream(uploadfile); byte[] buffer = new byte[1024 * 1024]; int length; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } in.close(); out.close(); return uploaddir.substring(1)+"\\"+filefilename; } catch (filenotfoundexception ex) { return null; } catch (ioexception ex) { return null; } } public static string getrandomstring(int length){ string str="abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789"; random random=new random(); stringbuffer sb=new stringbuffer(); for(int i=0;i<length;i++){ int number=random.nextint(62); sb.append(str.charat(number)); } return sb.tostring(); } }
除了单图上传还有多图上传,原理都是一样的
package com.cpsec.tang.chemical.action; import java.io.file; import java.io.fileinputstream; import java.io.filenotfoundexception; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import java.util.list; import javax.servlet.http.httpservletrequest; import org.apache.struts2.servletactioncontext; import com.opensymphony.xwork2.actionsupport; /** * 多文件上传 */ public class filesuploadaction extends actionsupport { //上传文件存放路径 private final static string uploaddir = "/upload"; //上传文件集合 private list<file> file; //上传文件名集合 private list<string> filefilename; //上传文件内容类型集合 private list<string> filecontenttype; public list<file> getfile() { return file; } public void setfile(list<file> file) { this.file = file; } public list<string> getfilefilename() { return filefilename; } public void setfilefilename(list<string> filefilename) { this.filefilename = filefilename; } public list<string> getfilecontenttype() { return filecontenttype; } public void setfilecontenttype(list<string> filecontenttype) { this.filecontenttype = filecontenttype; } public string uploadform() throws exception { httpservletrequest request = servletactioncontext.getrequest(); string webpath=null;//上传路径 for (int i = 0; i < file.size(); i++) { //循环上传每个文件 uploadfile(i); webpath="upload/"+this.getfilefilename().get(i); } return "success"; } //执行上传功能 private string uploadfile(int i) throws filenotfoundexception, ioexception { try { inputstream in = new fileinputstream(file.get(i)); string dir = servletactioncontext.getrequest().getrealpath(uploaddir); file filelocation = new file(dir); //此处也可以在应用根目录手动建立目标上传目录 if(!filelocation.exists()){ boolean iscreated = filelocation.mkdir(); if(!iscreated) { //目标上传目录创建失败,可做其他处理,例如抛出自定义异常等,一般应该不会出现这种情况。 return null; } } string filename=this.getfilefilename().get(i); file uploadfile = new file(dir, filename); outputstream out = new fileoutputstream(uploadfile); byte[] buffer = new byte[1024 * 1024]; int length; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } in.close(); out.close(); return uploadfile.tostring(); } catch (filenotfoundexception ex) { return null; } catch (ioexception ex) { return null; } } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!