jsp 图片上传功能实现原创
- 格式:doc
- 大小:40.50 KB
- 文档页数:5
┊┊┊┊┊┊┊┊┊┊┊┊┊装┊┊┊┊┊订┊┊┊┊┊线┊┊┊┊┊┊┊┊┊┊┊┊┊图片上传的设计与实现二.设计目的运用jsp开发工具和数据库开发一个小型的基于Web系统。
要求提交详细的设计说明书及各步骤所需图表和文档,对复杂的代码段和程序段,应画出程序流程图。
在界面设计中,画出每个窗口的布局。
通过本实践性教学环节,能较好地巩固jsp基本知识,jsp连接数据库实现动态网页。
三.需求分析如今时代,互联网已经进入我们的生活,而互联网上就有图片上传,显示,访问等等功能,有着很大的市场空间。
图片上传必须实现:1.数据库访问模块:利用JavaBean封装对数据库的操作,主要包括连接数据库、添加、删除、查询数据表、关闭连接等功能;2.上传模块:通过上传组件实现图片的上传。
3.显示模块:提供图片信息列表的显示效果。
4.查看模块:点击可以显示图片的内容。
四.总体设计图片上传是指客户端通过Web应用程序将本地图片资源传输到服务器上。
在客户端需要显示图片时,服务器端将图片通过网络以流的形式发送给客户端,然后利用不同的形式显示图片。
图片上传必须要对电子相册有,用户注册,用户注册,添加相片,修改相册,用户反馈,管理用户,如图1所示。
图1 总体设计┊┊┊┊┊┊┊┊┊┊┊┊┊装┊┊┊┊┊订┊┊┊┊┊线┊┊┊┊┊┊┊┊┊┊┊┊┊1.文件上传组件介绍文件上传组件是一些开源组织发布的针对实现文件上传功能的一组class 文件。
jspSmartUpload和Apache的common-fileupload是两个比较流行的文件上传组件。
这两个组件都可以在JSP中实现文件上传。
本节使用Apache的common-fileupload组件实现图片上传。
2.HTML中文件上传组件介绍HTML中<input type="file"/>元素可以创建文件上传组件。
该控件带有一个文本框和浏览按钮。
使用该组件时要注意以下几点。
3000分求JSP 图片上传/放大缩小/裁减的源代码guestdsf竹省省市滋发息加友铜牌会员1 # 大 中 小 发表于 2009-08-27 10:33:003000分求JSP 图片上传/放大缩小/裁减的源代码。
能裁减固定大小比如(120*100)的就行。
有预览,能显示图片长宽和大小(file size)最好。
本人结帖率是99.87%, 可用分8000+非常感谢!!如果没有JSP 源代码,PHP 源代码也可以。
package myBean; import java.io.*; public class uploadpic {String picPath;//图片路径 (如:F:picturea.gif ) public String pictype[];//设置图片的后缀名 FileInputStream in; int piclength;//设置图片的最大kb public void setpicPath(String picPath)//获得图片的路径 {this.picPath=picPath; } 设置图片的最大长度{this.piclength=piclength;}public int getpiclength(){return piclength;}public boolean testlength()//判断图片的长度是否大于设定的最大长度try{in=new FileInputStream(picPath);if(in.available()/1024>piclength)return false;}catch(IOException e){System.out.println(e.getMessage());}return true;}public void setpictype(String[] pictype)//设置图片的扩展名{this.pictype=pictype;}public boolean testpictype()//判断图片的扩展名是否是规定的{if(pictype!=null){for(int i=0;i <pictype.length;i ){if(picPath.endsWith(pictype))return true;}return false;}return false;}}以下是在jsp页面中调用uploadpic首先要引入此bean所在的包<%@page import="myBean.uploadpic" %><jsp:useBean id="pic" scope="page" class="myBean.uploadpic" /> 下一条语句是得到上一层页面,也就是用户提交的图片路径!picp=codetostring.codeToString(request.getParameter("picPath"));pic.setpicPath(picp);pic.setpiclength(100);//以kb为单位if(pic.testlength())out.print("length ok <br>");elseout.print("length ok");String p1,p2;p1=".jpg";p2=".gif";String[] type={p1,p2};pic.setpictype(type);if(pic.testpictype())out.print("typeok");elseout.print("type error");made by zonecens 不知道2楼的怎么样,我来学习一个!帮顶!好像百度一招很多百度一下,找到相关网页约11,400,000篇,用时0.036秒3000连个星星都升不了这个是JAVA代码package ftp;import .ftp.*;import .*;import java.awt.*;import java.awt.event.*;import java.applet.*;import java.io.*;class FTPextends Applet {FtpClient aftp;DataOutputStream outputs;TelnetInputStream ins;TelnetOutputStream outs;TextArea lsArea;Label LblPrompt;Button BtnConn;Button BtnClose;TextField TxtUID;TextField TxtPWD;TextField TxtHost;int ch;public String a = "没有连接主机";String hostname = "";public void init() {setBackground(Color.white);setLayout(new GridBagLayout());GridBagConstraints GBC = new GridBagConstraints();LblPrompt = new Label("没有连接主机");LblPrompt.setAlignment(Label.LEFT);BtnConn = new Button("连接");BtnClose = new Button("断开");BtnClose.enable(false);TxtUID = new TextField("", 15);TxtPWD = new TextField("", 15);TxtPWD.setEchoCharacter('*');TxtHost = new TextField("", 20);Label LblUID = new Label("User ID:");Label LblPWD = new Label("PWD:");Label LblHost = new Label("Host:");lsArea = new TextArea(30, 80);lsArea.setEditable(false);GBC.gridwidth = GridBagConstraints.REMAINDER;GBC.fill = GridBagConstraints.HORIZONTAL; ( (GridBagLayout) getLayout()).setConstraints(LblPrompt, GBC);add(LblPrompt);GBC.gridwidth = 1;( (GridBagLayout) getLayout()).setConstraints(LblHost, GBC);add(LblHost);GBC.gridwidth = GridBagConstraints.REMAINDER; ( (GridBagLayout) getLayout()).setConstraints(TxtHost, GBC);add(TxtHost);GBC.gridwidth = 1;( (GridBagLayout) getLayout()).setConstraints(LblUID, GBC);add(LblUID);GBC.gridwidth = 1;( (GridBagLayout) getLayout()).setConstraints(TxtUID, GBC);add(TxtUID);GBC.gridwidth = 1;( (GridBagLayout) getLayout()).setConstraints(LblPWD, GBC);add(LblPWD);GBC.gridwidth = 1;( (GridBagLayout) getLayout()).setConstraints(TxtPWD, GBC);add(TxtPWD);GBC.gridwidth = 1;GBC.weightx = 2;( (GridBagLayout) getLayout()).setConstraints(BtnConn, GBC);add(BtnConn);GBC.gridwidth = GridBagConstraints.REMAINDER;( (GridBagLayout) getLayout()).setConstraints(BtnClose, GBC);add(BtnClose);GBC.gridwidth = GridBagConstraints.REMAINDER;GBC.fill = GridBagConstraints.HORIZONTAL;( (GridBagLayout) getLayout()).setConstraints(lsArea, GBC);add(lsArea);}public boolean connect(String hostname, String uid,String pwd) {this.hostname = hostname;LblPrompt.setText("正在连接,请等待.....");try {aftp = new FtpClient(hostname);aftp.login(uid, pwd);aftp.binary();showFileContents();}catch (FtpLoginException e) {a = "无权限与主机:" + hostname + "连接!";LblPrompt.setText(a);return false;}catch (IOException e) {a = "连接主机:" + hostname + "失败!";LblPrompt.setText(a);return false;}catch (SecurityException e) {a = "无权限与主机:" + hostname + "连接!";LblPrompt.setText(a);return false;}LblPrompt.setText("连接主机:" + hostname + "成功!");return true;}public void stop() {try {aftp.closeServer();}catch (IOException e) {}}public void paint(Graphics g) {}public boolean action(Event evt, Object obj) { if (evt.target == BtnConn) {LblPrompt.setText("正在连接,请等待....."); if (connect(TxtHost.getText(), TxtUID.getText(), TxtPWD.getText())) {BtnConn.setEnabled(false);BtnClose.setEnabled(true);}return true;}if (evt.target == BtnClose) {BtnConn.enable(true);BtnClose.enable(false);LblPrompt.setText("与主机" + hostname + "连接已断开!");return true;}return super.action(evt, obj);}public boolean sendFile(String filepathname) { boolean result = true;if (aftp != null) {LblPrompt.setText("正在粘贴文件,请耐心等待....");String contentperline;try {a = "粘贴成功!";String fg = new String("\");int index = stIndexOf(fg);String filename = filepathname.substring(index + 1);File localFile;localFile = new File(filepathname); RandomAccessFile sendFile = new RandomAccessFile(filepathname, "r");//sendFile.seek(0);outs = aftp.put(filename);outputs = new DataOutputStream(outs); while (sendFile.getFilePointer() < sendFile.length()) {ch = sendFile.read();outputs.write(ch);outs.close();sendFile.close();}catch (IOException e) {a = "粘贴失败!";result = false;}LblPrompt.setText(a);showFileContents();}else {result = false;}return result;}public void showFileContents() {StringBuffer buf = new StringBuffer();lsArea.setText("");try {ins = aftp.list();while ( (ch = ins.read()) >= 0) { buf.append( (char) ch);}lsArea.appendText(buf.toString());ins.close();}catch (IOException e) {}}public static void main(String args[]) { Frame f = new Frame("FTP Client");f.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) { System.exit(0);}});FTP ftp = new FTP();ftp.init();ftp.start();f.add(ftp);f.pack();f.setVisible(true);}}2楼 2004-10-13 08:56 angel7532 [引用] [回复]这个是HTML网页<html><head><meta http-equiv="Content-Type" content="text/html; charset=GBK" /><title>FTP下载 </title><script type="text/javascript">var javawsInstalled = false;var isIE = false;var isICE = erAgent.indexOf("ICEBrowser") >=0;if (navigator.mimeTypes && navigator.mimeTypes.length) javawsInstalled = navigator.mimeTypes['application/x-java-jnlp-file'];elseisIE = true;function insertLink(url, name) {if (javawsInstalled) {document.write("<a href="" + url + "">" + name + " </a>");} else {if (isICE) {document.write("JBuilder's Web View does not support Web Start (no appropriate Web Start plugin is available). ");document.write("Other popular (external) browsers are supported");} else {document.write("Need to install Java Web Start");}document.write(" -- for more information, visit");document.write("<a href="/products/javawebstart/">" );document.write("the Java Web Start page");document.write(" </a>");}}</script><script type="text/vbscript">on error resume nextIf isIE ThenIf Not(IsObject(CreateObject("JavaWebStart.IsInstalled"))) ThenjavawsInstalled = falseElsejavawsInstalled = trueEnd IfEnd If</script></head><body><h1>Java Web Start application </h1> <script type="text/javascript"><!--insertLink("FTPEXE.jnlp","FTP下载");// --></script><noscript><a href="FTPEXE.jnlp">FTP下载 </a></noscript></body></html>3楼 2004-10-13 09:21 szabo [引用] [回复]angel7532(卡卡西):哪我服务器上要不要作一些配置或安装其他软件呢?4楼 2004-10-15 09:30 szabo [引用] [回复] 不能沉啊。
在用java开发企业器系统的使用,特别是涉及到与办公相关的软件开发的时候,文件的上传是客户经常要提到的要求.因此有一套很好文件上传的解决办法也能方便大家在这一块的开发.首先申明,该文章是为了自己记录一备以后开发需要的时候,不用手忙脚乱哈哈........现在在国内用的非常多的一般是两种方法解决来解决文件上传.cos.jar + uploadbean.jar + filemover.jar这个是用的非常普遍的,原因是因为他操作方便,是我们不必再去关注,那些文件的输入和输出流,使我们从底层的流中解脱出来.uploadfile,uploadbean,multipartformdatarequest<%@ page contenttype="text/html;charset=gb2312" %><head><title>fbysss uploadbean 示例</title><!--meta http-equiv="content-type" content="text/html; charset=iso-8859-1"--><!--meta http-equiv="content-type" content="text/html; charset=gb2312"--></head><form name="form1" method="post" action="sssupload.jsp" enctype="multipart/form-data"><input name="title" type= "text" value="中文字"><td class="bodystyle">附件</td><td class="bodystyle"> <input name="attach" type="file" id="attach" size="50" > </td><input name="ok" type= "submit" value="提交"></form>2.读取表单页面sssgetdata.jsp<!--//==================================================== ======================//文件:uploadbean上传实例//功能:解决中文乱码,完成文件上传,并提供上传改名解决方案//作者:fbysss//msn:jameslastchina@//==================================================== ======================--><%@ page contenttype="text/html;charset=gbk" %><%@ page language="java" import="com.jspsmart.upload.*"%><%@ page import="java.text.simpledateformat"%><%@ page import="java.io.file"%><%@ page import="java.util.*"%><%@ page import="javazoom.upload.*"%><%@ page import="uploadutilities.filemover"%><head><meta http-equiv="content-type" content="text/html; charset=gb2312"></head><%request.setcharacterencoding("gbk");//设置编码格式,就不用一个个转码了。
1.开发环境:1)eclipse3.2+tomcat5.5;2)创建dynamic web project;3)下载:Commons FileUpload 可以在/commons/fileupload/下载附加的Commons IO 可以在/commons/io/下载将commons-fileupload-1.2.1.jar commons-io-1.4.jar拷贝到WebContent\WEB-INF\\lib 目录;2.前台:<;form method=";post"; enctype=";multipart/form-data"; action=";upload.jsp"; target=";_blank";>;<;%-- 类型enctype用multipart/form-data,这样可以把文件中的数据作为流式数据上传,不管是什么文件类型,均可上传--%>;<;table>;<;tr>;<;td>;作品:<;input type=";file"; name=";upfile"; size=";50";>;<;/td>;<;/tr>;<;tr>;<;td>;作者:<;input type=";text"; name=";author"; size=";22";>;标题:<;input type=";text"; name=";title"; size=";22";>;<;input type=";submit"; name=";submit"; value=";上传";>;<;/td>;<;/tr>;<;tr>;<;td>;备注:上传的jpg图片(显示扩展名为.jpg)大小不能超过4M!<;/td>;<;/tr>; <;/table>;<;/form>;3.后台:1)引用:<;%@ page import=";mons.fileupload.servlet.ServletFileUpload";%>; <;%@ page import=";mons.fileupload.disk.DiskFileItemFactory";%>; <;%@ page import=";mons.fileupload.*";%>;2)代码:String id=null;//上传记录idString destinationfileName=null;//目标文件名String author=null;String title=null;int flag=0;//上传标志String uploadPath =request.getSession().getServletContext().getRealPath(";/";)+";upload/";;//图片上传路径String tempPath = request.getSession().getServletContext().getRealPath(";/";)+";upload/temp/";;//图片临时上传路径StringimagePath=request.getScheme()+";://";+request.getServerName()+";:";+request.getS erverPort()+request.getContextPath()+";/";; // 图片网络相对路径if(!new File(uploadPath).isDirectory()) new File(uploadPath).mkdirs();// 文件夹不存在就自动创建:if(!new File(tempPath).isDirectory())new File(tempPath).mkdirs();try {DiskFileUpload fu = new DiskFileUpload();fu.setSizeMax(4194304);// 设置最大文件尺寸,这里是4MBfu.setSizeThreshold(4096);// 设置缓冲区大小,这里是4kbfu.setRepositoryPath(tempPath);// 设置临时目录:List fileItems = fu.parseRequest(request);// 得到所有的文件:Iterator i = fileItems.iterator();while(i.hasNext()) {// 依次处理表单中每个域FileItem file = (FileItem)i.next();// 获得用户上传时文件名if (file.isFormField()){ //获得文本域表单数据if(";author";.equals(file.getFieldName()))author=codeToString(file.getString());if(";title";.equals(file.getFieldName())) title=codeToString(file.getString()); continue;//非file域不处理}String sourcefileName = file.getName();if( sourcefileName.endsWith(";.jpg";)){//生成上传后的文件名Random rd = new Random();Calendar time = Calendar.getInstance();id=String.valueOf(time.get(Calendar.YEAR))+ String.valueOf(time.get(Calendar.MONTH)+1)+ String.valueOf(time.get(Calendar.DAY_OF_MONTH))+ String.valueOf(time.get(Calendar.HOUR_OF_DAY))+ String.valueOf(time.get(Calendar.MINUTE))+ String.valueOf(time.get(Calendar.SECOND))+ String.valueOf(rd.nextInt(100));destinationfileName=id+";.jpg";;File fTmp=new File(uploadPath+destinationfileName);file.write(fTmp);//out.print(";<;img src=";+imagePath+";upload/";+destinationfileName+";>;";); flag=1;//上传成功标志1}else{out.print(";上传失败,只能上传jpg文件!";); }}//out.print(";<;script>;location.href=\";demo.jsp\";;<;/script>;";);}catch (IOException e) {out.print(";上传失败!";);}out.flush();out.close();4.主要解决点:1)问题:form设置enctype=";multipart/form-data";,request.getParameters函数无法获取表单域值;2)解决方案:if (file.isFormField()){ //获得文本域表单数据if(";author";.equals(file.getFieldName()))author=codeToString(file.getString());if(";title";.equals(file.getFieldName())) title=codeToString(file.getString()); continue;//非file域不处理}。
Struts1实现文件上传功能实现技术:Struts1.3+JSP主要实现:上传文件类型的前台验证,后台验证上传文件的类型、格式;实现图片的压缩和添加水印等功能。
JSP页面部分代码:(1)上传表单代码<form action='bk/image/addImage.do?method=add'method="post"enctype="multipart/form-data"><label for='imagename' >上传图片:</label><input type="file" class='formfield' name='imagename' id='imagename' /><span style="color: red; margin-left:40px;">* 只允许上传gif、jpg、bmp、png!</span> <input type="submit" value="提交" onclick="return SureSubmit(this.form)"/><input type="reset" value="重置" /></form>(2)JavaScript验证代码<script type="text/javascript">function verifyForm(objForm){//取得上传文本框的值var imagefile=objForm.imagename.value;//取得上传文件扩展名var ext=imagefile.substring(imagefile.length-3).toLowerCase();if (ext!="jpg" && ext!="gif" && ext!="bmp" && ext!="png"){alert("只允许上传gif、jpg、bmp、png!");return false;}return true;}function SureSubmit(objForm){//验证通过则提交表单if (verifyForm(objForm)) objForm.submit();return false;}</script>(3)/WEB-INF/UI/success.jsp代码<span style="color: red; font-size: 20px; font-weight: bold;">${suc }</span><a href="${backurl }">点击返回</a>(4)/WEB-INF/UI/fail.jsp代码<span style="color: red; font-size: 20px; font-weight: bold;">操作失败!${message }</span><a href="javascript:void(0)" onclick="javascript:window.history.go(-1);">单击返回前一页</a>Struts1中配置文件的配置<form-beans><form-bean name="imageForm" type="com.ImageForm"/></form-beans><action-mappings><action path="/bk/image/addImage" type="com.action.UploadAction" name="imageForm" scope="request" parameter="method"><forward name="fail" path="/WEB-INF/UI/fail.jsp"/><forward name="success" path="/WEB-INF/UI/success.jsp"/></action></action-mappings>后台代码(1)Domain Objectpackage com;import java.io.File;import java.io.FileOutputStream;import java.util.Arrays;import java.util.List;import org.apache.struts.action.ActionForm;import org.apache.struts.upload.FormFile;public class ImageForm extends ActionForm {/**图片路径**/private FormFile imagename;public FormFile getImagename() {return imagename;}public void setImagename(FormFile imagename) {this.imagename = imagename;}//验证上传图片的格式和类型public static boolean validateImageFileType(FormFile formFile) {if (formFile != null && formFile.getFileSize() > 0) {// 获取上传文件的后缀String ext = formFile.getFileName().substring(formFile.getFileName().lastIndexOf('.') + 1).toLowerCase();//允许上传的文件类型List<String> arrowType =Arrays.asList("image/bmp","image/png","image/gif","image/jpg","image/jpeg","image/pjpeg") ;//允许上传的文件后缀List<String> arrowExtension = Arrays.asList("gif","jpg","bmp","png");returnarrowType.contains(formFile.getContentType().toLowerCase())&&arrowExtension.contains(ext) ;}return true;}/**获取上传文件的后缀*/public static String getExt(FormFile formfile){returnformfile.getFileName().substring(formfile.getFileName().lastIndexOf('.')+1).toLowerCase() ;}/***保存文件*@param savedir存放目录*@param fileName文件名称*@param data保存的内容*@return保存的文件*@throws Exception*/public static File saveFile(File savedir, String fileName, byte[] data) throws Exception{ if(!savedir.exists()) savedir.mkdirs();//如果目录不存在就创建File file = new File(savedir, fileName);FileOutputStream fileoutstream = new FileOutputStream(file);fileoutstream.write(data);fileoutstream.close();return file;}}(2)Action文件的内容package com.action;import java.awt.Color;import java.io.File;import java.text.SimpleDateFormat;import java.util.Date;import java.util.UUID;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;import org.apache.struts.actions.DispatchAction;import org.apache.struts.upload.FormFile;import com.ImageForm;import com.util.ImageSizer;import com.util.WarterImage;public class UploadAction extends DispatchAction {/***添加图片*/public ActionForward add(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {ImageForm image = (ImageForm) form;// 获取到页面中传输过来的文件FormFile file = image.getImagename();if (!ImageForm.validateImageFileType(file)) {request.setAttribute("message", "文件格式不正确,只允许上传gif/jpg/png/bmp图片");return mapping.findForward("fail");}// 判断传过来的数据是否为空,如果为空,返回页面if (null != file.getFileName() && file.getFileSize() > 0&& file.getFileSize() < 204800) {// 我们要生成一个文件路径,我们应该把上传的文件放到一个文件夹内,路径第一如下upfile/images/2011/X/x/sss.xxSimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/HH/");String fileUrlDir = "/upfile/images/" + sdf.format(new Date());//得到图片保存目录的真实路径String fileUrl = request.getSession().getServletContext().getRealPath(fileUrlDir)+ "\\";System.out.println(fileUrl);String ext = ImageForm.getExt(file);String imagename = UUID.randomUUID().toString() + "." + ext;//构建文件名称ImageForm.saveFile(new File(fileUrl), imagename, file.getFileData());// 文件保存到服务器上的路径String imagePro = fileUrl + imagename;// 对图片进行压缩,如果传过来的数据为0,则使用默认值ImageSizer.resize(new File(imagePro), new File(imagePro), 120, ext);// 添加水印,这个路径要选择服务器的路径,保存要和保存图片的路径一致WarterImage.pressText("添加水印", imagePro, "宋体", 0, Color.black, 10, 0, 0);request.setAttribute("suc", "图片保存成功");return mapping.findForward("success");}// 判断图片不能太大else if (null != file.getFileName() && file.getFileSize() > 0) {request.setAttribute("message", "提交图片不能超过200k");return mapping.findForward("fail");}return mapping.findForward("fail");}}图片压缩和添加水印类(1)图片压缩package com.util;import java.awt.Color;import ponent;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.Image;import java.awt.MediaTracker;import java.awt.Toolkit;import java.awt.image.BufferedImage;import java.awt.image.ConvolveOp;import java.awt.image.Kernel;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import javax.imageio.ImageIO;import javax.swing.ImageIcon;import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGEncodeParam;import com.sun.image.codec.jpeg.JPEGImageEncoder;/***图像压缩工具**/public class ImageSizer {public static final MediaTracker tracker = new MediaTracker(new Component() { private static final long serialVersionUID = 1234162663955668507L;});/***@param originalFile原图像*@param resizedFile压缩后的图像*@param width图像宽*@param format图片格式jpg,png,gif(非动画)*@throws IOException*/public static void resize(File originalFile, File resizedFile, int width, String format) throws IOException {if(format!=null && "gif".equals(format.toLowerCase())){resize(originalFile, resizedFile, width, 1);return;}FileInputStream fis = new FileInputStream(originalFile);ByteArrayOutputStream byteStream = new ByteArrayOutputStream();int readLength = -1;int bufferSize = 1024;byte bytes[] = new byte[bufferSize];while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) {byteStream.write(bytes, 0, readLength);}byte[] in = byteStream.toByteArray();fis.close();byteStream.close();Image inputImage = Toolkit.getDefaultToolkit().createImage( in );waitForImage( inputImage );int imageWidth = inputImage.getWidth( null );if ( imageWidth < 1 )throw new IllegalArgumentException( "image width "+ imageWidth + " is out of range");int imageHeight = inputImage.getHeight( null );if ( imageHeight < 1 )throw new IllegalArgumentException( "image height " + imageHeight + " is out of range" );// Create output image.int height = -1;double scaleW = (double) imageWidth / (double) width;double scaleY = (double) imageHeight / (double) height;if (scaleW >= 0 && scaleY >=0) {if (scaleW > scaleY) {height = -1;} else {width = -1;}}Image outputImage = inputImage.getScaledInstance( width, height,java.awt.Image.SCALE_DEFAULT);checkImage( outputImage );encode(new FileOutputStream(resizedFile), outputImage, format);}/**Checks the given image for valid width and height.*/private static void checkImage( Image image ) {waitForImage( image );int imageWidth = image.getWidth( null );if ( imageWidth < 1 )throw new IllegalArgumentException( "image width "+ imageWidth + " is out of range");int imageHeight = image.getHeight( null );if ( imageHeight < 1 )throw new IllegalArgumentException( "image height "+ imageHeight + " is out of range"); }/**Waits for given image to e before querying image height/width/colors.*/ private static void waitForImage( Image image ) {try {tracker.addImage( image, 0 );tracker.waitForID( 0 );tracker.removeImage(image, 0);} catch( InterruptedException e ) { e.printStackTrace(); }}/**Encodes the given image at the given quality to the output stream.*/private static void encode( OutputStream outputStream, Image outputImage, String format )throws java.io.IOException {int outputWidth = outputImage.getWidth( null );if ( outputWidth < 1 )throw new IllegalArgumentException( "output image width " + outputWidth + " is out of range" );int outputHeight = outputImage.getHeight( null );if ( outputHeight < 1 )throw new IllegalArgumentException( "output image height "+ outputHeight + " is out of range" );// Get a buffered image from the image.BufferedImage bi = new BufferedImage( outputWidth, outputHeight,BufferedImage.TYPE_INT_RGB );Graphics2D biContext = bi.createGraphics();biContext.drawImage( outputImage, 0, 0, null );ImageIO.write(bi, format, outputStream);outputStream.flush();}/***缩放gif图片*@param originalFile原图片*@param resizedFile缩放后的图片*@param newWidth宽度*@param quality缩放比例(等比例)*@throws IOException*/private static void resize(File originalFile, File resizedFile, int newWidth, float quality) throws IOException {if (quality < 0 || quality > 1) {throw new IllegalArgumentException("Quality has to be between 0 and 1");}ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());Image i = ii.getImage();Image resizedImage = null;int iWidth = i.getWidth(null);int iHeight = i.getHeight(null);if (iWidth > iHeight) {resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight) / iWidth, Image.SCALE_SMOOTH);} else {resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight, newWidth, Image.SCALE_SMOOTH);}// This code ensures that all the pixels in the image are loaded.Image temp = new ImageIcon(resizedImage).getImage();// Create the buffered image.BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null),temp.getHeight(null),BufferedImage.TYPE_INT_RGB);// Copy image to buffered image.Graphics g = bufferedImage.createGraphics();// Clear background and paint the image.g.setColor(Color.white);g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));g.drawImage(temp, 0, 0, null);g.dispose();// Soften.float softenFactor = 0.05f;float[] softenArray = {0, softenFactor, 0, softenFactor, 1-(softenFactor*4), softenFactor, 0, softenFactor, 0};Kernel kernel = new Kernel(3, 3, softenArray);ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);bufferedImage = cOp.filter(bufferedImage, null);// Write the jpeg to a file.FileOutputStream out = new FileOutputStream(resizedFile);// Encodes image as a JPEG data streamJPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);param.setQuality(quality, true);encoder.setJPEGEncodeParam(param);encoder.encode(bufferedImage);}}(2)添加水印package com.util;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Image;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileOutputStream;import javax.imageio.ImageIO;import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGImageEncoder;public class WarterImage {public WarterImage() {}/****把图片印刷到图片上**@param pressImg--*水印文件*@param targetImg--*目标文件*@param x*--X坐标*@param y*--y坐标*/public final static void pressImage(String pressImg, String targetImg,int x, int y) {try {// 目标文件File _file = new File(targetImg);Image src = ImageIO.read(_file);// 获取图片的宽度int wideth = src.getWidth(null);// 获取图片的高度int height = src.getHeight(null);BufferedImage image = new BufferedImage(wideth, height,BufferedImage.TYPE_INT_RGB);Graphics g = image.createGraphics();g.drawImage(src, 0, 0, wideth, height, null);// 水印文件File _filebiao = new File(pressImg);Image src_biao = ImageIO.read(_filebiao);// 获取水印图片的宽度int wideth_biao = src_biao.getWidth(null);// 获取水印图片的高度int height_biao = src_biao.getHeight(null);// 如果传输过来的坐标值为x==-1,y==-1,则水印图片添加到左下角if (x == -1 && y == -1) {g.drawImage(src_biao, wideth - wideth_biao, height- height_biao, wideth_biao, height_biao, null);} else {g.drawImage(src_biao, x, y, wideth_biao, height_biao, null);}// 水印文件结束g.dispose();FileOutputStream out = new FileOutputStream(targetImg);JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);encoder.encode(image);out.close();} catch (Exception e) {e.printStackTrace();}}/****************************************************************************打印文字水印图片**@param pressText*--文字*@param targetImg--*目标图片*@param fontName--*字体名*@param fontStyle--*字体样式*@param color--*字体颜色字体大小*@param x*x坐标轴*@param y*y坐标轴*/public static void pressText(String pressText, String targetImg,String fontName, int fontStyle, Color color, int fontSize, int x,int y) {try {System.out.println(targetImg);File _file = new File(targetImg);Image src = ImageIO.read(_file);int wideth = src.getWidth(null);int height = src.getHeight(null);BufferedImage image = new BufferedImage(wideth, height,BufferedImage.TYPE_INT_RGB);Graphics g = image.createGraphics();g.drawImage(src, 0, 0, wideth, height, null);if (color == null) {g.setColor(Color.black);} else {g.setColor(color);}g.setFont(new Font(fontName, fontStyle, fontSize));// 判断输入的是中文还是英文,因为英文和中文所占的像素比例不一样,所以需要设置一下,美观漂亮byte[] bytes = pressText.getBytes();int i = bytes.length;// i为字节长度int j = pressText.length();// j为字符长度// 如果i==j 说明是英文字符if (i == j) {g.drawString(pressText, (int) (wideth- (fontSize * (pressText.length() / 2.0)) - x), height- y);} else {g.drawString(pressText, (int) (wideth- (fontSize * pressText.length()) - x), height - y);}g.dispose();FileOutputStream out = new FileOutputStream(targetImg);JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);encoder.encode(image);out.close();} catch (Exception e) {System.out.println(e);}}}。
现在想写个程序向数据库中插入图片路径(或则插入图片也可以)最好是插入图片的路径这样可插入任意大的图片...请高手指点一下思路..感激不尽1.通过显示层向数据库中插入图片2.在界面显示的时候是小图片(缩小过的)3.当点击查看大图片会显示图片(原来的大小)提供给你图片上传和显示的代码吧!希望对你有帮助我在程序代码里贴了向Mysql数据库写入image代码的程序,可是好多人都是Java的初学者,对于这段代码,他们无法将它转换成jsp,所以我在这在写一下用jsp怎样向数据库写入图像文件。
大家先在数据库建这样一张表,我下面的这些代码对任何数据库都通用,只要支持blob类型的只要大家将连接数据库的参数改一下就可以了。
SQL> create table image(id int,content varchar(200),image blob);如果在sqlserver2000的数据库中,可以将blob字段换为image类型,这在SqlServer2000中是新增的。
testimage.html文件内容如下:<HTML><HEAD><TITLE> Image File </TITLE><meta http-equiv= "Content-Type " content= "text/html; charset=gb2312 "></HEAD><FORM METHOD=POST ACTION= "testimage.jsp "><INPUT TYPE= "text " NAME= "content "> <BR><INPUT TYPE= "file " NAME= "image "> <BR><INPUT TYPE= "submit "> </FORM><BODY></BODY></HTML>我们在Form的action里定义了一个动作testimage.jsp,它的内容如下:<%@ page contentType= "text/html;charset=gb2312 "%><%@ page import= "java.sql.* " %><%@ page import= "java.util.* "%><%@ page import= "java.text.* "%><%@ page import= "java.io.* "%><html><%Class.forName( "org.gjt.mm.mysql.Driver ").newInstance();String url= "jdbc:mysql://localhost/mysql?user=root&password=&useUnicode=true&characterEncoding=885 9_1 ";//其中mysql为你数据库的名字,user为你连接数据库的用户,password为你连接数据库用户的密码,可自己改Connection conn= DriverManager.getConnection(url);String content=request.getParameter( "content ");String filename=request.getParameter( "image ");FileInputStream str=new FileInputStream(filename);String sql= "insert into test(id,content,image) values(1,?,?) ";PreparedStatement pstmt=dbconn.conn.prepareStatement(sql);pstmt.setString(1,content);pstmt.setBinaryStream(2,str,str.available());pstmt.execute();out.println( "Success,You Have Insert an Image Successfully ");%>下面我写一个测试image输出的例子看我们上面程序写的对不对,testimageout.jsp的内容如下:<%@ page contentType= "text/html;charset=gb2312 "%><%@ page import= "java.sql.* " %><%@ page import= "java.util.* "%><%@ page import= "java.text.* "%><%@ page import= "java.io.* "%><html><body><%Class.forName( "org.gjt.mm.mysql.Driver ").newInstance();String url= "jdbc:mysql://localhost/mysql?user=root&password=&useUnicode=true&characterEncoding=885 9_1 ";//其中mysql为你数据库的名字,user为你连接数据库的用户,password为你连接数据库用户的密码,可自己改Connection conn= DriverManager.getConnection(url);String sql = "select image from test where id =1 ";Statement stmt=null;ResultSet rs=null;try{stmt=conn.createStatement();rs=stmt.executeQuery(sql);}catch(SQLException e){}while(rs.next()) {res.setContentType( "image/jpeg ");ServletOutputStream sout = response.getOutputStream();InputStream in = rs.getBinaryStream(1);byte b[] = new byte[0x7a120];for(int i = in.read(b); i != -1;){sout.write(b);in.read(b);}sout.flush();sout.close();}}catch(Exception e){System.out.println(e);}%></body></html>你运行这个程序,你就会看到刚才你写入美丽的图片就会显示在你面前。
首先下载jsmartcom_zh_CN.jar /hijackwust然后将其解压,并放到项目web-inf下面的lib目录下,之后到myeclipse的项目下导入jar包到项目下。
JSP+Mysql+jspsmart=上传图片并生成略缩图片然后记录到数据库原代码代码是由网上找的,然后自己修改了一下将输入的信息以及图片路径保存到数据库。
根目录必须预先有2个文件夹存在1。
pc 文件夹 --> 用来装上传的正本图片2。
pc2 文件夹 --> 用来装缩小的图片希望对大家有用~~jspsmart插件下栽地址/upfile*************.rar将web-inf 这个目录下面的那个jspsmart包,放入你自己的.classess文件夹里面放的位置是:tomcat\网站根目录\WEB-INF\classes\com\jspsmart\uploadupimg.jsp--------------------------------------------------------------------------------------<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>上传文件</title></head><body><table border="0" align="center" cellpadding="0" cellspacing="0"><tr><td height="45" align="center" valign="middle"><formaction="uploadimage.jsp" method="post" enctype="multipart/form-data" name="form1"><p>上传人姓名(注意上面加红色的代码一定要加,否则获取页面就得不到参数)<input name="name" type="text" id="name" onpaste="return false;" style='border: 1px solid #CCCCCC; font-size:9pt;margin-top:4px;ime-mode:disabled;' size="20"onfocusout="if(isSearch(this.value))this.focus()" /></p><p>请选择上传的图片<input type="file" name="file"><input type="submit" name="Submit" value="上传"></p></form></td></tr></table></body></html>===================================================================== =======uploadimage.jsp--------------------------------------------------------------------------------------<%@ page contentType="text/html;charset=gb2312" language="java" import="java.io.*,java.awt.Image,java.awt.image.*,com.sun.image.codec .jpeg.*,java.sql.*,com.jspsmart.upload.*,java.util.*"%><jsp:useBean id="db" scope="page" class="classmate.DB"/><html><head><title>文件上传处理页面</title><meta http-equiv="Content-Type" content="text/html; charset=gb2312"> </head><bord><%SmartUpload mySmartUpload =new SmartUpload();long file_size_max=4000000;String fileName2="",ext="",testvar="";String url="pc/"; //应保证在根目录中有此目录的存在//初始化mySmartUpload.initialize(pageContext);//只允许上载此类文件try {mySmartUpload.setAllowedFilesList("jpg,gif");//上载文件mySmartUpload.upload();} catch (Exception e){%><SCRIPT language=javascript>alert("只允许上传.jpg和.gif类型图片文件");window.location=''upfile.jsp'';</script><%}try{com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0); if (myFile.isMissing()){%><SCRIPT language=javascript>alert("请先选择要上传的文件");window.location=''upfile.jsp'';</script><%}//String myFileName=myFile.getFileName(); //取得上载的文件的文件名ext= myFile.getFileExt(); //取得后缀名int file_size=myFile.getSize(); //取得文件的大小String str1=mySmartUpload.getRequest().getParameter("name"); //获得上传的人名称!String saveurl="";if(file_size<file_size_max){//更改文件名,取得当前上传时间的毫秒数值Calendar calendar = Calendar.getInstance();String filename = String.valueOf(calendar.getTimeInMillis());saveurl=request.getRealPath("/")+url;saveurl+=filename+"."+ext; //保存路径myFile.saveAs(saveurl,mySmartUpload.SAVE_PHYSICAL);//out.print(filename);//-----------------------上传完成,开始生成缩略图-------------------------java.io.File file = new java.io.File(saveurl); //读入刚才上传的文件String url2="pc2/";String newurl=request.getRealPath("/")+url2+filename+"."+ext; //新的缩略图保存地址String weburl=filename+"."+ext; //保存数据库路径Image src =javax.imageio.ImageIO.read(file); //构造Image 对象float tagsize=100;old_w=src.getWidth(null); //得到源图宽int old_h=src.getHeight(null);int new_w=0;int new_h=0; //得到源图长int tempsize;float tempdouble;if(old_w>old_h){tempdouble=old_w/tagsize;}else{tempdouble=old_h/tagsize;}new_w=Math.round(old_w/tempdouble);new_h=Math.round(old_h/tempdouble);//计算新图长宽BufferedImage tag = newBufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);tag.getGraphics().drawImage(src,0,0,new_w,new_h,null); //绘制缩小后的图FileOutputStream newimage=new FileOutputStream(newurl); //输出到文件流JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(newimage);encoder.encode(tag); //近JPEG编码newimage.close();String sql="insert into pc(name,url,day) values ('"+str1+"','"+ weburl +"',NOW())";db.executeUpdate(sql);%>yes ok!!<%}else{out.print("<SCRIPT language=''javascript''>");out.print("alert(''上传文件大小不能超过"+(file_size_max/1000)+"K'');");out.print("window.location=''upfile.jsp;''"); out.print("</SCRIPT>");}}}catch (Exception e){e.toString();}%></bord></html>。
js控件Kindeditor实现图⽚⾃动上传功能Kindeditor本⾝提供了许多⾮常实⽤的插件,由于代码开源,开发⼈员可以根据需要对其进⾏任意扩展和修改。
在使⽤Kindeditor编辑⽹站内容时考虑这样⼀个场景:编辑⼈员往往会从其它页⾯或者Word⽂档将内容复制到Kindeditor编辑器中,⽽不会从⼀张⽩纸开始编写内容。
如果所复制的内容中包含图⽚,则需要⾸先将图⽚从源地址下载到本地,然后将其上传到本⽹站所在的服务器,否则图⽚仍然会指向你所复制的页⾯或者⽂档,这会导致图⽚可能在页⾯中⽆法正确打开。
编辑⼈员往往要处理许多的⽂档,这样的操作⽆疑⾮常繁琐。
能否让Kindeditor⾃动识别粘贴到其中的内容,并将图⽚⾃动上传到服务器呢?下⾯的代码实现了这⼀功能。
有关如何在页⾯中使⽤Kindeditor可以去查看官⽅⽹站的⽂档,这⾥不再详细介绍。
实现该功能的基本思路:在Kindeditor编辑器的keyup事件中添加代码,以检查编辑器的内容中是否包含图⽚;找出需要⾃动上传到服务器的图⽚,通过Ajax⽅式调⽤图⽚上传程序将图⽚上传到服务器;在Ajax的回调函数中将对应图⽚的src地址修改为本地相对地址。
该功能不⽀持将Word中的图⽚复制出来并上传到服务器。
上图是最终实现效果。
程序会⾃动识别编辑器中的内容,如果有图⽚需要上传,则会在编辑器的顶部显⽰⼀条提⽰信息。
⽤户点击“上传”链接,程序会通过Ajax请求调⽤图⽚上传程序,并在回调函数中将对应图⽚的src地址修改为本地相对地址。
具体实现步骤及相关代码:1. Kindeditor编辑器修改找到kindeditor.js⽂件,在keyup()事件中添加⾃定义代码。
不同版本的Kindeditor所提供的代码差别可能会⽐较⼤,需要借助于官⽅⽂档进⾏查找。
本⽂基于Kindeditor 4.1.10版本。
2. auto.js⽂件代码function df() {var haspicContainer = document.getElementById("has_pic");if (haspicContainer == null) {haspicContainer = document.createElement("div");haspicContainer.id = "has_pic";haspicContainer.innerHTML = "<input type='text' id='piclist' value='' style='display:none;'/><div id='upload'><b>您有图⽚需要上传到服务器</b> <a href='javascript:uploadpic();' >上传</a></div><div id='confirm'></div>"; $(".ke-toolbar").after(haspicContainer);}var img = $(".ke-edit-iframe").contents().find("img");var piccount = 0;var sstr = "";$(img).each(function (i) {var that = $(this);if (that.attr("src").indexOf("http://") >= 0 || that.attr("src").indexOf("https://") >= 0) {piccount++;if (i == $(img).length - 1)sstr += that.attr("src");elsesstr += that.attr("src") + "|";}});$("#piclist").val(sstr);document.getElementById("has_pic").style.display = (piccount > 0) ? "block" : "none";}function closeupload() {$("#has_pic").hide();$("#upload").show();}function uploadpic() {var piclist = encodeURI($("#piclist").val());if (piclist.length == 0) return false;$.ajax({url: "/uploadpic.ashx",data: "pic=" + piclist,type: "GET",beforeSend: function () {$("#upload").hide();$("#confirm").text("正在上传中...");},success: function (msg) {if (msg !== "") {var str = new Array();str = msg.split('|');var img = $(".ke-edit-iframe").contents().find("img");$(img).each(function (i) {var that = $(this);if (that.attr("src").indexOf("http://") >= 0 || that.attr("src").indexOf("https://") >= 0) {that.attr("src", "/uploads/image/" + str[i]);that.attr("data-ke-src", "/uploads/image/" + str[i]);}});$("#confirm").html(img.length + "张图⽚已经上传成功! <a href='javascript:closeupload();'>关闭</a>");}else $("#confirm").text("上传失败!");}});}其中的$(".ke-edit-iframe").contents().find("img")⽤来查找编辑器内容中的所有图⽚。
package com.lsl.util;import java.awt.Image;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import javax.imageio.ImageIO;import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGEncodeParam;import com.sun.image.codec.jpeg.JPEGImageEncoder;/**** @author Administrator* 图像处理类*/public class PicCompression {/*** 压缩图片方法** @param oldFile* 将要压缩的图片的绝对地址* @param width* 压缩宽* @param height* 压缩长* @param quality* 压缩清晰度<b>建议为1.0</b>* @param smallIcon* 压缩图片后,添加的扩展名* @return*/public String zoom(String oldFile, int width, int height, float quality) {if (oldFile == null) {return null;}String newImage = null;try {File file = new File(oldFile);if(!file.exists()) //文件不存在时return null;/** 对服务器上的临时文件进行处理*/Image srcFile = ImageIO.read(file);// 为等比缩放计算输出的图片宽度及高度double rate1 = ((double) srcFile.getWidth(null)) / (double) width+ 0.1;double rate2 = ((double) srcFile.getHeight(null)) / (double) height+ 0.1;double rate = rate1 > rate2 ? rate1 : rate2;int new_w = (int) (((double) srcFile.getWidth(null)) / rate);int new_h = (int) (((double) srcFile.getHeight(null)) / rate);/** 宽,高设定*/BufferedImage tag = new BufferedImage(new_w, new_h,BufferedImage.TYPE_INT_RGB);tag.getGraphics().drawImage(srcFile, 0, 0, new_w, new_h, null);String filePrex = oldFile.substring(0, stIndexOf('.'));/** 压缩后的文件名*/// newImage =smallIcon + filePrex// +oldFile.substring(filePrex.length());newImage = filePrex+width+"x"+height + oldFile.substring(filePrex.length());// newImage = smallIcon;/** 压缩之后临时存放位置*/FileOutputStream out = new FileOutputStream(newImage);JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);/** 压缩质量*/jep.setQuality(quality, true);encoder.encode(tag, jep);out.close();srcFile.flush();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return newImage;}}package com.lsl.goods.action;import java.io.File;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import javax.annotation.Resource;import mons.io.FileUtils;import org.apache.struts2.ServletActionContext;import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Controller;import com.lsl.bean.GoodsInfo;import com.lsl.bean.Lsluser;import com.lsl.service.GoodsInfoService;import com.lsl.util.PicCompression;import com.opensymphony.xwork2.ActionContext;@Controller @Scope("prototype")public class SetGoodsPicAction {@Resource GoodsInfoService goodsInfoService;private File image; // 上传的文件如果多文件就用数组形式File[] imageprivate String imageFileName; // 上传的文件名如果多文件就用数组形式String[] imageFileName 这里用来获取文件的后缀名private String imageContentType; //上传文件的类系如果多文件就用数组形式String[] imageContentType//注意文件的大小不再这里设置在struts.xml配置上传文件的大小public File getImage() {return image;}public void setImage(File image) {this.image = image;}public String getImageFileName() {return imageFileName;}public void setImageFileName(String imageFileName) {this.imageFileName = imageFileName;}public String getImageContentType() {return imageContentType;}public void setImageContentType(String imageContentType) {this.imageContentType = imageContentType;}//设置图片public String setGoodsPic() throws IOException{if(image !=null){if(imageContentType.indexOf("image") != -1){ //检测是否为图片String path="/Images/goodsImgs/";String imageBasePath = ServletActionContext.getServletContext().getRealPath(path);Lsluser lu= (Lsluser)ActionContext.getContext().getSession().get("currentUser");String privatePath =lu.getLslId().toString();String realPath=imageBasePath+"\\"+privatePath; //硬盘的目录这里第一个\是转译符意思是第二个\是有效字符SimpleDateFormat dateFormat =new SimpleDateFormat("yyyyMMddHHmmssSSS");String imageName=dateFormat.format(new Date()); //设置文件名以时间命名StringsuffixName=imageFileName.substring(stIndexOf(".")).toLowerCase();//获取文件的后缀名File saveFile= new File(new File(realPath),imageName+suffixName);if(!saveFile.getParentFile().exists()) saveFile.getParentFile().mkdirs();//如果不存在绝对目录那就创建改目录FileUtils.copyFile(image, saveFile); //保存原图成功PicCompression pc = new PicCompression(); //处理图片的类int w=200;int h=250;pc.zoom(newFile(realPath).toString()+"\\"+imageName+suffixName,w,h,1); //生成缩略图命名规则就是在原图的名字后面加上宽度x长度String bigPicRelativePath = path + privatePath+"/"+imageName+suffixName; //实图的相对路径用于存放进数据库String smallPicRelativePath = path + privatePath+"/"+imageName+w+"x"+h+suffixName; //缩略图的相对路径用于存放进数据库GoodsInfoaddingGoods=(GoodsInfo)ActionContext.getContext().getSession().get("addingGoods");addingGoods.setImgUrl(bigPicRelativePath);addingGoods.setSmallImgUrl(smallPicRelativePath);goodsInfoService.update(addingGoods);ActionContext.getContext().getSession().put("setPicRestul", "图片上传成功");}}return "setPicSuccess";}}AnyQuestion --- Qq:16895920。