Java简单上传图片例子

前台页面:
<!--注意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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值