利用File类进行文件上传

第一步:
在jsp页面中,注意负责上传文件的控件要使用html:file标签,在html:form处注意加上enctype=“multipart/form-data” method为post
1、
<html:form method="post" action="/save_user" enctype="multipart/form-data" >
2、
<tr>
<td>头像:</td>
<td><html:file property="image" /></td>
</tr>

第二步:
在对应的表单form中定义private FormFile image属性,当然自动生成set和get方法。

第三步:
在pojo中声明一个属性与上传控件对应。

第四步:
在相应的Action中的方法里加入上传的代码:
例如:
UserForm userForm = (UserForm) form;
UserDAO dao = new UserDAO();
String message = null;
String basePath = this.getServlet().getServletContext()
.getRealPath("/");
//获取项目根路径
try {
dao.getSession().beginTransaction();
User temp = (User) dao.findByUserName(userForm.getUserName());
if (temp == null) {
User user = new User();
userForm.fillToUserBean(user);
if (userForm.getImage().getFileName().length() > 0) {
//判断是否有选择上传文件,如果有则文件长度>0
String path = "/uploadImages/" +
//这里的"/uploadImages/"指的是什么?它是我们自行在WebRoot下面创建的用于存放上传文件的文件夹的名称,即:如果我们将上传的文件存放在uploadfile中,我们要做的是在WebRoot下新建一个名为uploadfile的文件夹,并且这里的代码要改为:"/uploadfile/"
dao.picturePath(userForm.getImage());
//这里我们用到了一个自己在DAO中写的名为picturePath的方法,其目的是为了将上传的文件跟换一个不会和数据库已有数据重复的文件名称,这样的好处是即使上传的多个文件实质上一个,但有需要将其区分开时比较方便。再介绍完Action的写法之后我们再来讲解DAO中方法的写法。
String endstring = userForm.getImage().getFileName()
.substring(
userForm.getImage().getFileName()
.lastIndexOf(".") + 1);
if ("jpg".equals(endstring) || "png".equals(endstring)
|| "gif".equals(endstring)) {
try {
dao.saveFile(userForm.getImage(), basePath, path);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
user.setHeaderImg(path);
} else {
user.setHeaderImg("");
}
}
dao.save(user);
dao.getSession().getTransaction().commit();
return mapping.findForward("index");


第五步
在DAO中我们需要修改saveFile,添加picturePath方法,具体代码如下:
saveFile
public void saveFile(FormFile formfile, String basePath, String path)
throws IOException {
FileOutputStream fos = null;
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
fos = new FileOutputStream(basePath + path);
in = new BufferedInputStream(formfile.getInputStream());
out = new BufferedOutputStream(fos);
byte[] buf = new byte[8192];
int readsize;
while ((readsize = in.read(buf)) != -1) {
out.write(buf, 0, readsize);
out.flush();
}

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fos != null)
try {
fos.close();
} catch (Exception err) {
err.printStackTrace();
}
if (in != null)
try {
in.close();
} catch (Exception err) {
err.printStackTrace();
}
if (out != null)
try {
out.close();
} catch (Exception err) {
err.printStackTrace();
}

}
}

picturePath
public String picturePath(FormFile formfile) {
String filename = "";
UUIDGenerator g = new UUIDGenerator();
// UUIDGenerator是我们自行编写的一个自动生成名字的一个类,之后会给出具体代码。
filename = formfile.getFileName();
if (filename.length() > 0) {
filename = filename.substring(filename.lastIndexOf("."));
}
filename = (String) g.generate() + filename;
return filename;
}



第六步:
编写工具类:UUIDGenerator
import java.io.Serializable;
import java.net.InetAddress;

public class UUIDGenerator {

private static final int IP;
public static int IptoInt( byte[] bytes ) {
int result = 0;
for (int i=0; i<4; i++) {
result = ( result << 8 ) - Byte.MIN_VALUE + (int) bytes[i];
}
return result;
}
static {
int ipadd;
try {
ipadd = IptoInt( InetAddress.getLocalHost().getAddress() );
}
catch (Exception e) {
ipadd = 0;
}
IP = ipadd;
}
private static short counter = (short) 0;
private static final int JVM = (int) ( System.currentTimeMillis() >>> 8 );

public UUIDGenerator() {
}
protected int getJVM() {
return JVM;
}
protected short getCount() {
synchronized(UUIDGenerator.class) {
if (counter<0) counter=0;
return counter++;
}
}
protected int getIP() {
return IP;
}
protected short getHiTime() {
return (short) ( System.currentTimeMillis() >>> 32 );
}
protected int getLoTime() {
return (int) System.currentTimeMillis();
}

private final static String sep = "";

protected String format(int intval) {
String formatted = Integer.toHexString(intval);
StringBuffer buf = new StringBuffer("00000000");
buf.replace( 8-formatted.length(), 8, formatted );
return buf.toString();
}

protected String format(short shortval) {
String formatted = Integer.toHexString(shortval);
StringBuffer buf = new StringBuffer("0000");
buf.replace( 4-formatted.length(), 4, formatted );
return buf.toString();
}

public Serializable generate() {
return new StringBuffer(36)
.append( format( getIP() ) ).append(sep)
.append( format( getJVM() ) ).append(sep)
.append( format( getHiTime() ) ).append(sep)
.append( format( getLoTime() ) ).append(sep)
.append( format( getCount() ) )
.toString();
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值