<img src="images/hi.png"/>
1. 上传图片到服务器的文件系统中
2. 把图片的地址保存到数据库
3. 读取图片的地址,设置到<img src=".."/>的src属性中
java web开发中,使用文件 *** 作类来上传图片并读取,如下代码:
* @desc: 图片处理工具* @author: bingye
* @createTime: 2015-3-17 下午04:25:32
* @version: v1.0
*/
public class ImageUtil {
/**
* 将图片写到客户端
* @author: bingye
* @createTime: 2015-3-17 下午04:36:04
* @history:
* @param image
* @param response void
*/
public static void writeImage(byte[] image,HttpServletResponse response){
if(image==null){
return
}
byte[] buffer=new byte[1024]
InputStream is=null
OutputStream os=null
try {
is=new ByteArrayInputStream(image)
os=response.getOutputStream()
while(is.read(buffer)!=-1){
os.write(buffer)
os.flush()
}
} catch (IOException e) {
e.printStackTrace()
} finally{
try {
if(is!=null){is.close()}
if(os!=null){os.close()}
} catch (IOException e) {
e.printStackTrace()
}
}
}
/**
* 获取指定路劲图片
* @author: bingye
* @createTime: 2015-3-21 上午10:50:44
* @param filePath
* @param response void
*/
public static void writeImage(String filePath,HttpServletResponse response){
File imageFile=new File(filePath)
if(imageFile!=null && imageFile.exists()){
byte[] buffer=new byte[1024]
InputStream is=null
OutputStream os=null
try {
is=new FileInputStream(imageFile)
os=response.getOutputStream()
while(is.read(buffer)!=-1){
os.write(buffer)
os.flush()
}
} catch (FileNotFoundException e) {
e.printStackTrace()
} catch (IOException e) {
e.printStackTrace()
} finally{
try {
if(is!=null){is.close()}
if(os!=null){os.close()}
} catch (IOException e) {
e.printStackTrace()
}
}
}
}
/**
* 图片上传到文件夹
* @author: bingye
* @createTime: 2015-3-20 下午08:07:25
* @param file
* @param savePath
* @return boolean
*/
public static ResultDto uploadToLocal(CommonsMultipartFile file,String savePath){
if(file!=null && !file.isEmpty()){
//获取文件名称
String fileName=file.getOriginalFilename()
//获取后缀名
String suffixName=fileName.substring(fileName.indexOf(".")+1)
//新名称
String newFileName=System.currentTimeMillis()+"."+suffixName
//新文件路劲
String filePath=savePath+newFileName
//获取存储文件路径
File fileDir=new File(savePath)
if(!fileDir.exists()){
//如果文件夹没有:新建
fileDir.mkdirs()
}
FileOutputStream fos=null
try {
fos=new FileOutputStream(filePath)
fos.write(file.getBytes())
fos.flush()
return ResultUtil.success("UPLOAD_SUCCESS", URLEncoder.encode(newFileName,"utf-8"))
} catch (Exception e) {
e.printStackTrace()
return ResultUtil.fail("UPLOAD_ERROR")
} finally{
try {
if(fos!=null){
fos.close()
}
} catch (IOException e) {
e.printStackTrace()
return ResultUtil.fail("UPLOAD_ERROR")
}
}
}
return ResultUtil.fail("UPLOAD_ERROR")
}
}
我们使用一些已有的组件帮助我们实现这种上传功能。常用的上传组件:
Apache 的 Commons FileUpload
JavaZoom的UploadBean
jspSmartUpload
以下,以FileUpload为例讲解
1、在jsp端
<form id="form1" name="form1" method="post" action="servlet/fileServlet" enctype="multipart/form-data">
要注意enctype="multipart/form-data"
然后只需要放置一个file控件,并执行submit *** 作即可
<input name="file" type="file" size="20" >
<input type="submit" name="submit" value="提交" >
2、web端
核心代码如下:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8")
DiskFileItemFactory factory = new DiskFileItemFactory()
ServletFileUpload upload = new ServletFileUpload(factory)
try {
List items = upload.parseRequest(request)
Iterator itr = items.iterator()
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next()
if (item.isFormField()) {
System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8"))
} else {
if (item.getName() != null &&!item.getName().equals("")) {
System.out.println("上传文件的大小:" + item.getSize())
System.out.println("上传文件的类型:" + item.getContentType())
System.out.println("上传文件的名称:" + item.getName())
File tempFile = new File(item.getName())
File file = new File(sc.getRealPath("/") + savePath, tempFile.getName())
item.write(file)
request.setAttribute("upload.message", "上传文件成功!")
}else{
request.setAttribute("upload.message", "没有选择上传文件!")
}
}
}
}catch(FileUploadException e){
e.printStackTrace()
} catch (Exception e) {
e.printStackTrace()
request.setAttribute("upload.message", "上传文件失败!")
}
request.getRequestDispatcher("/uploadResult.jsp").forward(request, response)
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)