图片的上传:
实现上传图片的html文件.
enctype="multipart/form-data 代表二进制接受表单流.
<form action="upload.action" method="post" enctype="multipart/form-data">
<input type="file" name="usericon">
<br /> <input type="submit" value="upload">
</form>
Action:主要作用是接受参数,好像必须是File的name,然后配上FileName和ContentType这两个属性。
setter和getter方法自动生成。
要配置Spring中的uploadIconServiceImp,注解可用。
uploadIconServiceImp的uploadandseticon来处理,action负责传递参数。
@Autowired
private UploadServiceImp uploadIconServiceImp;
private File usericon;
private String usericonFileName;
private String usericonContentType;
public String uploadIcon() {
return uploadIconServiceImp.uploadandseticon(usericon,usericonFileName, usericonContentType);
}
UploadIconServiceImp的作用实现对数据的处理。
public String uploadandseticon(File usericon, String usericonFileName,
String usericonContentType) {
// TODO Auto-generated method stub
try {
// 判断session中是否存在用户.
InputStream is = new FileInputStream(usericon);
String uploadPath = ServletActionContext.getServletContext()
.getRealPath("/icon");
File dic = new File(uploadPath);
dic.mkdirs();
File toFile = new File(uploadPath, usericonFileName);
System.out.println();
OutputStream os = new FileOutputStream(toFile);
byte[] buffer = new byte[1024 * 1024];
int length = 0;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
System.out.println("上传文件名" + usericonContentType);
System.out.println("上传文件类型" + usericonFileName);
is.close();
os.close();
return "success";
}
实现把文件放到指定的文件夹里面,如果需要写入数据库的话,可以用连接形式,也可以BLOB的存放。