您的位置:首页 > 编程语言 > Java开发

Java简单上传图片例子

2011-08-24 14:44 423 查看
前台页面:

<!--注意enctype表明设置表单的MIME编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;只有使用了multipart/form-data,才能完整的传递文件数据,进行下面的操作.-->
<form id="addform" method="post" enctype="multipart/form-data" action="${base}/action/addPhoPic">
<table border="0" class="perview" align="center">
<a href="#" onClick="toaddpic()">上传至相册</a>
<tr>
<th>选择文件</th>
<th width="50%">预览图</th>
</tr>
<tr>
<td height="200"><input id="idFile" name="upload" type="file" /></td>
<td align="center"><img id="idImg" /></td>
</tr>
</table>
</form>

Java后台处理:

//与前台页面空间name一致
private File upload;
//反射,得到文件类型,文件名称
private String uploadContentType;
private String uploadFileName;
public String doAddPhoPic(){
//自己的PhotoService接口处理
IPhotoService photoService=BeanFactory.getBean(BeanConstants.WB_PHOTO_SERVICE);
Photo photo=new Photo();
//这里简单的demo没有要把名字规范,也没有对图片有剪切或缩小处理,所以就简单的把上传的图片以1,2,3命名
int count=photoService.queryPhotoList().size();
count++;
String file_path1="";
String file_path2="";
try {
//上传至该项目所在本地目录
file_path1=Constants.BASE_ROOT+"/fullsize"+"/"+count+".jpg";
file_path2=Constants.BASE_ROOT+"/thumbs"+"/"+count+".jpg";
photo.setPicName(photoService.queryPhotoList().size()+1+".jpg");
photo.setPicUrl(file_path2);
photoService.insertPhoto(photo);
System.out.println("---"+file_path1);
System.out.println("---"+file_path2);
//对文件进行写操作
FileOutputStream fos1=new FileOutputStream(file_path1);
FileOutputStream fos2=new FileOutputStream(file_path2);
//对文件进行读操作
FileInputStream fis=new FileInputStream(upload);
byte[] buffer=new byte[1024];
int len=0;
//读入流,保存至byte数组
while((len=fis.read(buffer))>0){
fos1.write(buffer,0,len);
fos2.write(buffer,0,len);
}
fos1.close();
fos2.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
list=photoService.queryPhotoList();
return SUCCESS;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息