上传图片并生成缩略图

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/woshimuyi1025/article/details/52413425

需求:上传图片到服务器的images目录,并在images目录下按照年月日存储原始图片和生成的缩略图。

上传的图片名称修改为:时间+随机数+.jpg    缩略图名称修改为:thum_ + 时间+随机数+.jpg

效果如下:



项目目录如下:


项目地址:http://pan.baidu.com/s/1eSmcHk2

主要的代码如下:

ThumbnailAction代码:

package com.thumbnail;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.UUID;

import javax.servlet.http.HttpSession;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/")
public class ThumbnailAction {
	@Autowired
	private UploadService uploadService;
	@Autowired
	private ThumbnialService thumbnialService;
	
	@RequestMapping(value="/thumbnail",method=RequestMethod.POST)
	public ModelAndView thumbnail(@RequestParam("image")CommonsMultipartFile file, HttpSession session) throws Exception{
		//获取当前时间
		Calendar now = Calendar.getInstance();
        int yyyy = now.get(Calendar.YEAR);
        int mm = now.get(Calendar.MONTH)+1;
        int d = now.get(Calendar.DAY_OF_MONTH);
        String path = yyyy+"/"+mm+"/"+d;
		//相对路径
		String uploadPath = "/images/"+path;
		//绝对路径
		String realUploadPath = session.getServletContext().getRealPath(uploadPath);
		
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		String tpmc =format.format(System.currentTimeMillis())+ UUID.randomUUID().toString()+".jpg";//图片存储的名字
		System.out.println("文件名"+tpmc);
		File saveFile = new File(new File(realUploadPath), tpmc);
		File dayfile =saveFile.getParentFile();
		 if(!dayfile.exists())
		{
			dayfile.mkdirs();
		}				
		//原图访问路径
		String imageUrl = uploadService.uploadImage(file, uploadPath, realUploadPath,tpmc);
		//缩略图访问路径
		String thumbImageUrl = thumbnialService.thumbnail(file, uploadPath, realUploadPath,tpmc);;
		
		ModelAndView mav = new ModelAndView();
		mav.addObject("imageURL",imageUrl);
		mav.addObject("thumbImageURL", thumbImageUrl);
		
		mav.setViewName("thumbnail");
		return mav;
		
	}
}

ThumbnialService代码:

package com.thumbnail;

import java.io.InputStream;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.Thumbnails.Builder;

@Service
public class ThumbnialService {
	public static final int WIDTH = 150;
	public static final int HEIGHT = 170;
	/**
	 * 
	 * @param file文件
	 * @param uploadPath相对路径
	 * @param realUploadPath绝对路径
	 * @param tpmc存储的缩略图的名称
	 * @return
	 */
	public String thumbnail(CommonsMultipartFile file, String uploadPath, String realUploadPath,String tpmc){
		try {
			String des = realUploadPath+"/thum_"+tpmc;
			Thumbnails.of(file.getInputStream()).size(WIDTH, HEIGHT).toFile(des);//设置缩略图的宽度和高度
			Builder<? extends InputStream> thumbnail = Thumbnails.of(file.getInputStream());
			thumbnail.size(WIDTH, HEIGHT);
			thumbnail.toFile(des);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return uploadPath+"/thum_"+tpmc;
	}
}
UploadService代码:

package com.thumbnail;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Service
public class UploadService {
	/**
	 * 
	 * @param file文件
	 * @param uploadPath相对路径
	 * @param realUploadPath绝对路径
	 * @param tpmc存储的缩略图的名称
	 * @return
	 */
	public String uploadImage(CommonsMultipartFile file, String uploadPath, String realUploadPath,String tpmc){
		InputStream is = null;
		OutputStream os = null;
		
		try {
			is = file.getInputStream();
			String des = realUploadPath+"/"+tpmc;
			os = new FileOutputStream(des);
			
			byte[] buffer = new byte[1024];
			while(is.read(buffer)>0){
				os.write(buffer);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(is!=null){
				try {
					is.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			if(os!=null){
				try {
					os.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
		return uploadPath+"/"+tpmc;
	}
}

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上传文件</title>
</head>
<body>
	<div class="demo">
		<div class="dheader">
			<h2>--图片上传--</h2>
		</div>
		<div class="dbody">
			<form id="upload_form" enctype="multipart/form-data" method="post" action="${pageContext.request.contextPath}/thumbnail">
				<h2>请选择上传图片</h2>
				<div>
					<input type="file" name="image" id="image" />
					<input type="submit" value="上传" />
				</div>
			</form>
		</div>
	</div>
</body>
</html>

thumbnail.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>操作结果</title>
</head>
<body>
	<h4>图片信息</h4>
	<hr/>
	<table width="100%">
		<tr>
			<td width="50%" align="center">
				<img src="${pageContext.request.contextPath}${imageURL}">
			</td>
			<td width="50%" align="center">
				<img src="${pageContext.request.contextPath}${thumbImageURL}">
			</td>
		</tr>
	</table>
	<a href="${pageContext.request.contextPath}">返回</a>
</body>
</html>



猜你喜欢

转载自blog.csdn.net/woshimuyi1025/article/details/52413425