在jsp中:
<tr>
<td bgColor="#66f94c">头像:</td>
<td><input type="file" name="file"> </td>
</tr>
在action中:
// 把数据插入数据库
public void upload() {
String root = ServletActionContext.getRequest().getRealPath("/upload");
try {
InputStream is = new FileInputStream(file);
// 创建一个文件,路径为root,文件名叫fileFileName
fileFileName = System.currentTimeMillis()
+ fileFileName.substring(fileFileName.lastIndexOf("."));
System.out.println(fileFileName);
File destFile = new File(root, fileFileName);
// 将文件输出到指定的目录
System.out.println(destFile.getAbsolutePath());
// 开始上传
OutputStream os = new FileOutputStream(destFile);
byte[] buffer = new byte[50000];
int length = 0;
// enctype="multipart/form-data"
while (-1 != (length = is.read(buffer))) {
os.write(buffer, 0, length);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
is.close();
os.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}