java图片的上传_java实现图片上传到服务器并修改图片样式

FileItemFactory factory = newDiskFileItemFactory();//创建文件上传处理器

ServletFileUpload upload = newServletFileUpload(factory);//开始解析请求信息

List items = null;try{

items=upload.parseRequest(request);

}catch(FileUploadException e) {

e.printStackTrace();

}//对所有请求信息进行判断

Iterator iter =items.iterator();while(iter.hasNext()) {

FileItem item=(FileItem) iter.next();//信息为普通的格式

if(item.isFormField()) {

String fieldName=item.getFieldName();

String value=item.getString();

request.setAttribute(fieldName, value);

}//信息为文件格式

else{

String fileName=item.getName();

String suffix= fileName.substring(fileName.lastIndexOf('.'));//图片名

System.out.println("图片名字"+fileName);//后缀名

System.out.println(suffix);int index = fileName.lastIndexOf("\");

fileName= fileName.substring(index + 1);

request.setAttribute("realFileName", fileName);//图片url

String basePath = getServletConfig().getServletContext().getRealPath("/")+"img";

System.out.println(basePath);//新文件名

String newFileName = new Date().getTime() +suffix;

System.out.println(newFileName);

File file= newFile(basePath, newFileName);try{

item.write(file);int userId = (Integer) request.getSession().getAttribute("id");

System.out.println("userId:" +userId);//存图片信息

imagsTT.ImagsUp(userId, newFileName,basePath);

session.setAttribute("imgurl", "img/" +newFileName);

System.out.print("用图片返回查询的数据"+"img/" +newFileName);

}catch(Exception e) {

e.printStackTrace();

}

}

request.setAttribute("msg","文件上传成功!");

getServletContext().getRequestDispatcher("/My.jsp").forward(request, response);return;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值