我也是google和百度和很久一点一点弄的……,希望能帮助到你。
直接看代码吧……
<tr>
<td align="right">图片:</td><td> <form:hidden path="picPath" id="picPath"></form:hidden>
<span id="${uuid}-statusPic" style="color: #666;">
<a href="javascript:void(0)" onclick="window.smartMenu.insert.replaceString()">预览</a></span>
<a class="easyui-linkbutton" onclick="$('#${uuid}-uploadWindow').window('open')">修改</a>
</td>
</tr>
<!-- 点击修改调出窗口 -->
<div id="${uuid}-uploadWindow" class="easyui-window" title="图片上传" modal="true" resizable="false" collapsible="false" minimizable="false" maximizable="false" closed="true" style="width:520px;height:100px;padding:5px;background: #fafafa;">
<div class="easyui-layout with iframe" fit="true">
<div region="center" border="false" style="padding:10px;background:#fff;border:1px solid #ccc;">
<form action="menu/SmartMenu.do?action=uploadFile" method="post" enctype="multipart/form-data" style="color: #666;" id="${uuid}-tforma">
<input type="hidden" name="picPath" id="${uuid}-picPath" value="${command.picPath}"/>
图片路径: <input type="file" name="itemPic" alt="" accept="image/*" id="${uuid}-itemPic">图片大小不超过2M<input class="easyui-linkbutton" type="submit" value="上传">
</form>
</div>
</div>
</div>
<!-- 页面刚刚加载时调用 -->
init: function(uuid) {
// this.identifier 是设定的全局变量,uuid是页面加载时的唯一编码
this.identifier = uuid;
// 图片上传
var idf = this.identifier;
var that = this;
$('#'+idf+'-tforma').ajaxForm({
dataType : 'json',
beforeSubmit : function(a, f, o) {
$('#'+idf+'-statusPic').html('上传中...');
},
success : function(data) {
if (typeof (data) == 'string')
data = eval('(' + data + ')');
$('#'+idf+'-uploadWindow').window('close');
if ("success" == data.message) {
$('div[identifier='+that.identifier+']').find('#picPath').val(data.path);
$("#"+idf+"-path").val(data.path);
$("#"+idf+"-statusPic").html( "<a target='window' href='" + data.path .replace( "\\", "/") + "'>预览</a>");
} else if ("error" == data.message)
$("#"+idf+"-statusPic").html("非图片数据!");
else
$("#"+idf+"-statusPic").html("上传数据错误!");
$("#"+idf+"-itemPic").val('');
},
error : function(jqXHR, textStatus,errorThrown) {
$('#$'+idf+'-uploadWindow').window('close');
//console.log("error:"+ data.responseText);
//console.log("status:" + textStatus);
$("#"+idf+"-statusPic").html("上传失败!");
$("#"+idf+"-itemPic").val('');
} });
}
/** * <b>商品上传指定的图片</b> * * @param request * @param response * @param command * @return * @throws Exception */public ModelAndView uploadFile(HttpServletRequest request, HttpServletResponse response, SmartMenu command) throws Exception {PrintWriter writer = null;try {response.setContentType("application/json; charset=GBK");writer = response.getWriter(); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;String source = request.getSession().getServletContext().getRealPath("/");// 获得第1张图片(根据前台的name名称得到上传的文件)MultipartFile imgFile1 = multipartRequest.getFile("itemPic");// 判断是否是重复上传图片(如果重复将删除旧图片)String sourceImg = request.getParameter("path");if (imgFile1.getContentType().split("/")[0].equals("image")) {if (null != sourceImg && !"".equals(sourceImg)) {System.out.println("旧图片路径:" + sourceImg);File f = new File(source + sourceImg);if (f.isFile()) {f.delete();System.out.println(" 删除成功");} elseSystem.out.println(" 删除失败!");}String path = null;if (imgFile1 != null && imgFile1.getSize() > 0) {path = this.getSmartMenuService().storeFile(request.getSession(), imgFile1);}writer.print("{\"message\":\"success\",\"path\":\"" + path.replace("\\", "\\\\") + "\"}");} elsewriter.print("{\"message\":\"error\"}");} catch (Exception e) {// TODO: handle exceptionwriter.print("{\"message\":\"no\"}");}writer.flush();writer.close();return null; }@Overridepublic String storeFile(HttpSession session, MultipartFile file) throws Exception {// TODO Auto-generated method stubString fileType = file.getContentType().split("/")[1];String path = session.getServletContext().getRealPath("/");String separator = File.separator;String uuid = UUID.randomUUID().toString();FileOutputStream fos = null;String fileName = null;try {InputStream fis = file.getInputStream();// 转换文件为png格式,并保存在同名目录下File files = new File(path + "\\dishpic");// 判断文件夹是否存在,如果不存在则创建文件夹if (!files.exists()) {files.mkdir();}if (file.getContentType().split("/")[0].equals("image")) {if (path.endsWith(separator))fileName = path + "dishpic" + separator + uuid + ".png";elsefileName = path + separator + "dishpic" + separator + uuid + ".png";fos = new FileOutputStream(fileName);ImageUtil.convertFormat(fis, fos, fileType, "png", 0, 0);fos.flush();fos.close();}} catch (Exception ex) {System.out.println("文件取出失败,错误信息: " + ex.getMessage());if (fos != null)fos.close();throw ex;}return "dishpic" + separator + uuid + ".png";}/** * <b>1.对图片时行格式转换</b><br/> * <b>2.对图片进行适度的大小裁剪</b> * */public class ImageUtil {/** * * @param infile 输入文件 * @param outfile 输出文件 * @param srcFormat 源格式 * @param destFormat 输出格式 * @return * @throws Exception */public static boolean convertFormat(InputStream infile,OutputStream outfile, String srcFormat, String destFormat, int width ,int height) throws Exception {boolean flag = false;BufferedImage src = ImageIO.read(infile);if(height > 0 && width > 0) {// compress the origin image if width and height are non-zeroheight = src.getHeight() > height ? height: src.getHeight();width = src.getWidth() > width ? width : src.getWidth();Image image = src.getScaledInstance(width, height, Image.SCALE_DEFAULT);//这个是用来进行图片大小调整的BufferedImage tag = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);Graphics g = tag.getGraphics();//可在下面对图片进行绘制和更改g.drawImage(image, 0, 0, null); // 绘制缩小后的图g.dispose();tag.flush();flag = ImageIO.write(tag, destFormat, outfile);// 输出到经过缩放的文件流} else {flag = ImageIO.write(src, destFormat, outfile);//输出原分辨率的图片}Logger.getLogger(ImageUtil.class).info("图片转换成功: 从[" + srcFormat + "]到[" + destFormat + "]");return flag;}}
<!-- xml中要配置这段代码 -- >
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>2048576</value>
</property>
</bean>
该代码是经测试使用的源码,但是还存在问题!我直接截的图片能够上传,修改过的图片不能上传,会报错
在
BufferedImage src = ImageIO.read(infile);ImageIO读jpg的时候出现javax.imageio.IIOException: Unsupported Image Type !