使用struts2及xheditor实现文件、图片上传(支持拖拽上传)

合集下载

用JSP实现拖拽上传文件和文件夹

用JSP实现拖拽上传文件和文件夹

用JSP实现拖拽上传文件和文件夹JSP(JavaServer Pages)是一种动态网页技术,允许将Java代码嵌入到HTML页面中。

拖拽上传文件和文件夹是一种常见的网页交互功能,可以使用JSP来实现。

在实现拖拽上传文件和文件夹功能之前,首先需要了解一下拖拽上传的基本原理。

在HTML中,可以通过Drag and Drop API来获取拖拽的文件和文件夹。

然后,可以使用JavaScript将拖拽的文件和文件夹发送到服务器端,服务器端可以使用JSP来处理这些文件和文件夹。

以下是一个基本的实现拖拽上传文件的JSP页面的示例:```htmlpageEncoding="UTF-8"%><!DOCTYPE html><html><head><meta charset="UTF-8"><title>拖拽上传文件</title><script>function handleDrop(event)event.preventDefault(; // 禁止浏览器打开文件var files = event.dataTransfer.files;//遍历上传的文件for (var i = 0; i < files.length; i++)var file = files[i];// 创建FormData对象,用于发送文件到服务器var formData = new FormData(;formData.append("file", file);// 创建一个XMLHttpRequest对象,发送文件到服务器var xhr = new XMLHttpRequest(;xhr.open("POST", "upload.jsp", true);xhr.onreadystatechange = functioif (xhr.readyState == 4 && xhr.status == 200)//上传成功console.log(xhr.responseText);}};xhr.send(formData);}}</script></head><body ondragover="event.preventDefault(;"ondrop="handleDrop(event);"><h1>拖拽上传文件</h1><p>将文件拖拽到此处上传</p></body></html>```当文件被拖拽到页面的时候,`handleDrop(`函数会被调用。

struts文件上传

struts文件上传

然后在struts.xml文件中加一句话
<constant name="struts.custom.i18n.resources" value="fileuploadmessages"/>
该属源文件,则多个资源文件的文件名以英文逗号(,)隔开。
配置文件代码
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "/dtds/struts-2.3.dtd"> <struts> <constant name="struts.i18n.encoding" value="gbk"/> <package name="fileupload" extends="struts-default" namespace="/"> <action name="fileupload" class="org.myfileupload.action.FileUpLoadAction" > <param name="savePath">/upload</param> <result name="success">/success.jsp</result> </action> </package> </struts> 配置上传文件的保存路

Struts2文件上传

Struts2文件上传
Struts2文件上传
1
文件上传与下载(单文件与多文件上传)
目标
2
struts2并没有定义自己的文件解析器,而是采用 了其他的开源组件 支持三种文件上传组件
# struts.multipart.parser=cos # struts.multipart.parser=pell struts.multipart.parser=jakarta 其中jakarta是默认支持的方式
Struts2文件下载
文件下载实质是将服务器上的文件以流的形式传送给客 户端浏览器,并通知浏览器如何处理文件流. 通过response对象通知浏览器的处理方式为下载
response.setHeader("Content-disposition", "attachment; filename=" + utf8File);
<s:form action="fileupload.action" enctype="multipart/formdata" method="post"> <s:textfield label="照片描述" name="desc"></s:textfield> <s:file label="文件1" name="file1"></s:file> <s:submit value="上传"></s:submit> </s:form>
<form action="fileupload.action" enctype="multipart/form-data" method="post"> 头像:<input type="file" name="image"> 头像描述:<input type="text" name="desc"> <input type="submit" value="上传"/> </form>

struts2文件上传文件类型设置

struts2文件上传文件类型设置

struts2是根据contentType来限制的,并不是文件的扩展名比如我想仅上传image/png,image/gif,image/jpeg这三种文件类型第一种方法是通过javascript校验来限制,这个比较简单,获取input的value 然后截取扩展名进行判断即可第二种是根据struts2自带的fileupload拦截器中提供的allowedTypes来进行限制,步骤如下:1 配置fileupload拦截器struts2的defaultStack中已经含有fileupload拦截器,如果想加入allowedTypes 参数,需要从新写一个defaultstack ,拷贝过来修改一下即可:<interceptor-stack name="myDefaultStack"><interceptor-ref name="exception"/><interceptor-ref name="alias"/><interceptor-ref name="servletConfig"/><interceptor-ref name="i18n"/><interceptor-ref name="prepare"/><interceptor-ref name="chain"/><interceptor-ref name="debugging"/><interceptor-ref name="profiling"/><interceptor-ref name="scopedModelDriven"/><interceptor-ref name="modelDriven"/><interceptor-ref name="fileUpload"><param name="allowedTypes">image/png,image/gif,image/jpeg</param></interceptor-ref><interceptor-ref name="checkbox"/><interceptor-ref name="staticParams"/><interceptor-ref name="actionMappingParams"/><interceptor-ref name="params"><paramname="excludeParams">dojo\..*,^struts\..*</param></interceptor-ref><interceptor-ref name="conversionError"/><interceptor-ref name="validation"><paramname="excludeMethods">input,back,cancel,browse</param></interceptor-ref><interceptor-ref name="workflow"><paramname="excludeMethods">input,back,cancel,browse</param></interceptor-ref></interceptor-stack></interceptors><default-interceptor-refname="myDefaultStack"></default-interceptor-ref>仅修改代码中的<interceptor-ref name="fileUpload"><param name="allowedTypes">image/png,image/gif,image/jpeg</param></interceptor-ref>上面配置的是上传文件类型的限制,其实共有两个参数maximumSize (可选) - 这个拦截器允许的上传到action中的文件最大长度(以byte为单位). 注意这个参数和在webwork.properties中定义的属性没有关系,默认2MBallowedTypes (可选) - 以逗号分割的contentType类型列表(例如text/html),这些列表是这个拦截器允许的可以传到action中的contentType.如果没有指定就是允许任何上传类型.2 jsp页面定义如下(testFileUpload.jsp)<s:form action="testFileUpload" method="post"enctype="multipart/form-data"><s:file name="file"theme="simple"/><s:fielderror name="file"></s:fielderror><s:submit/></s:form>3 后台的action声明如下(我用的是struts2的注解进行action配置)public class TestFileUploadAction extends ActionSupport{private File file;private String fileContentType;private String fileFileName;@Action(value = "testFileUpload", results = {@Result(name = "input", location = "/testFileUpload.jsp"),@Result(name = "success", location ="/testFileUploadSuccess.jsp")})public String execute() {return SUCCESS;}get/set......}注意:如果jsp中file的name="xxx",那么后台action中的属性要做相应更改为private File xxx;private String xxxContentType;private String xxxFileName;同时注意大小写一定要一致4 定义错误文件类型的消息提示,这个需要用到struts2的资源文件,在struts.properties文件中加入struts.custom.i18n.resources=globalMessagesglobalMessages对应着资源文件名5 在源文件夹下定义资源文件globalMessages.properties,并在里面加入如下信息:struts.messages.error.content.type.not.allowed=upload file contenttype is invalidate这里稍作说明(拷贝一下struts2的帮助):如果你的action实现了ValidationAware接口(如果action继承了ActionSupport,那么就相当于实现了ValidationAware),这个拦截器就可以添加几种字段错误.这些错误信息是基于存储在struts-messages.properties文件中的一些i18n值,这个文件是所有i18n请求的默认文件.你可以在自己消息文件的复写以下key的消息文字struts.messages.error.uploading - 文件不能上传的通用错误信息rge - 上传文件长度过大的错误信息struts.messages.error.content.type.not.allowed - 当上传文件不符合指定的contentType以上配置完毕后,测试一下,对于非法的contentType,例如xxx.log这个文件的的contentType是pplication/octet-stream会给出提示:upload file contenttype is invalidate'.a' : 'application/octet-stream','.ai' : 'application/postscript','.aif' : 'audio/x-aiff','.aifc' : 'audio/x-aiff','.aiff' : 'audio/x-aiff','.au' : 'audio/basic','.avi' : 'video/x-msvideo','.bat' : 'text/plain','.bcpio' : 'application/x-bcpio','.bin' : 'application/octet-stream','.bmp' : 'image/x-ms-bmp','.c' : 'text/plain','.cdf' : 'application/x-cdf','.cdf' : 'application/x-netcdf','.cpio' : 'application/x-cpio','.csh' : 'application/x-csh','.css' : 'text/css','.dll' : 'application/octet-stream', '.doc' : 'application/msword', '.dot' : 'application/msword','.dvi' : 'application/x-dvi','.eml' : 'message/rfc822','.eps' : 'application/postscript', '.etx' : 'text/x-setext','.exe' : 'application/octet-stream', '.gif' : 'image/gif','.gtar' : 'application/x-gtar','.h' : 'text/plain','.hdf' : 'application/x-hdf','.htm' : 'text/html','.html' : 'text/html','.ief' : 'image/ief','.jpe' : 'image/jpeg','.jpeg' : 'image/jpeg','.jpg' : 'image/jpeg','.js' : 'application/x-javascript', '.ksh' : 'text/plain','.latex' : 'application/x-latex','.m1v' : 'video/mpeg','.man' : 'application/x-troff-man', '.me' : 'application/x-troff-me', '.mht' : 'message/rfc822','.mhtml' : 'message/rfc822','.mif' : 'application/x-mif','.mov' : 'video/quicktime','.movie' : 'video/x-sgi-movie','.mp2' : 'audio/mpeg','.mp3' : 'audio/mpeg','.mpa' : 'video/mpeg','.mpe' : 'video/mpeg','.mpeg' : 'video/mpeg','.mpg' : 'video/mpeg','.ms' : 'application/x-troff-ms', '.nc' : 'application/x-netcdf', '.nws' : 'message/rfc822','.o' : 'application/octet-stream','.obj' : 'application/octet-stream','.oda' : 'application/oda','.p12' : 'application/x-pkcs12','.p7c' : 'application/pkcs7-mime','.pbm' : 'image/x-portable-bitmap','.pdf' : 'application/pdf','.pfx' : 'application/x-pkcs12','.pgm' : 'image/x-portable-graymap', '.pl' : 'text/plain','.png' : 'image/png','.pnm' : 'image/x-portable-anymap', '.pot' : 'application/vnd.ms-powerpoint', '.ppa' : 'application/vnd.ms-powerpoint', '.ppm' : 'image/x-portable-pixmap','.pps' : 'application/vnd.ms-powerpoint', '.ppt' : 'application/vnd.ms-powerpoint', '.ps' : 'application/postscript','.pwz' : 'application/vnd.ms-powerpoint', '.py' : 'text/x-python','.pyc' : 'application/x-python-code','.pyo' : 'application/x-python-code','.qt' : 'video/quicktime','.ra' : 'audio/x-pn-realaudio','.ram' : 'application/x-pn-realaudio', '.ras' : 'image/x-cmu-raster','.rdf' : 'application/xml','.rgb' : 'image/x-rgb','.roff' : 'application/x-troff','.rtx' : 'text/richtext','.sgm' : 'text/x-sgml','.sgml' : 'text/x-sgml','.sh' : 'application/x-sh','.shar' : 'application/x-shar','.snd' : 'audio/basic','.so' : 'application/octet-stream','.src' : 'application/x-wais-source', '.sv4cpio': 'application/x-sv4cpio','.sv4crc' : 'application/x-sv4crc','.swf' : 'application/x-shockwave-flash', '.t' : 'application/x-troff','.tar' : 'application/x-tar','.tcl' : 'application/x-tcl','.tex' : 'application/x-tex','.texi' : 'application/x-texinfo','.texinfo': 'application/x-texinfo','.tif' : 'image/tiff','.tiff' : 'image/tiff','.tr' : 'application/x-troff','.tsv' : 'text/tab-separated-values', '.txt' : 'text/plain','.ustar' : 'application/x-ustar','.vcf' : 'text/x-vcard','.wav' : 'audio/x-wav','.wiz' : 'application/msword','.wsdl' : 'application/xml','.xbm' : 'image/x-xbitmap','.xlb' : 'application/vnd.ms-excel', '.xls' : 'application/excel','.xls' : 'application/vnd.ms-excel', '.xml' : 'text/xml','.xpdl' : 'application/xml','.xpm' : 'image/x-xpixmap','.xsl' : 'application/xml','.xwd' : 'image/x-xwindowdump', '.zip' : 'application/zip',。

使用数组实现struts2组图上传

使用数组实现struts2组图上传

在实际项目中,由于要上传的图片比较多,我们需要对图片名称做一些处理,以避免图片名称相同,造成后者覆盖前者的意外。

所以action中我们可以这样写:Java代码1.package bag;2.3.import java.io.File;4.import java.io.FileInputStream;5.import java.io.FileOutputStream;6.import java.util.Date;7.8.import org.apache.struts2.ServletActionContext;9.10.import com.opensymphony.xwork2.ActionSupport;11.12.public class ManyUploadAction extends ActionSupport {13. private static final int BUFFER_SIZE = 16 * 1024;14.15. // 使用File数组封装多个文件域对应的文件内容16. private File[] file;17.18. // 使用字符串数组封装多个文件域对应的文件名19. private String[] fileFileName;20.21. // 接受依赖注入的属性22. private String savePath;23.24. // 结果显示消息25. private String msg;26.27. // 只用这个方法也可以实现多图片上传功能28. public String execute() throws Exception {29.30. // 取得需要上传的文件数组31. File[] files = this.getFile();32. // 遍历每个需要上传的文件33. for (int i = 0; i < files.length; i++) {34. fileFileName[i] = i + new Date().getTime()35. + getExtention(fileFileName)[i];36. // 以服务器的文件保存地址和原文件名建立上传文件输出流37. FileOutputStream fos = new FileOutputStream(getSavePath() + "\\"38. + getFileFileName()[i]);39. System.out.println(getSavePath() + "\\" + getFileFileName()[i]);40. // 以每个需要上传的文件建立文件输入流41. FileInputStream fis = new FileInputStream(files[i]);42. // 将每个需要上传的文件写到服务器对应的文件中43. byte[] buffer = new byte[BUFFER_SIZE];44. int len = 0;45. while ((len = fis.read(buffer)) > 0) {46. fos.write(buffer, 0, len);47. }48. }49. this.msg = "上传成功!";50. return SUCCESS;51. }52.53. // 获得每个文件的扩展名54. public String[] getExtention(String[] fileNames) {55. String[] extentions = new String[fileNames.length];56. for (int i = 0; i < extentions.length; i++) {57. int pos = fileNames[i].lastIndexOf(".");58. extentions[i] = fileNames[i].substring(pos);59. }60. return extentions;61. }62.63. public File[] getFile() {64. return file;65. }66.67. public void setFile(File[] file) {68. this.file = file;69. }70.71. public String[] getFileFileName() {72. return fileFileName;73. }74.75. public void setFileFileName(String[] fileFileName) {76. this.fileFileName = fileFileName;77. }78.79. public String getSavePath() {80. return ServletActionContext.getRequest().getRealPath(savePath);81. }82.83. public void setSavePath(String savePath) {84. this.savePath = savePath;85. }86.87. public String getMsg() {88. return msg;89. }90.91. public void setMsg(String msg) {92. this.msg = msg;93. }94.95.}这时注意到 execute方法中的fileFileName[i] ,我们给它以毫秒时间进行命名,但意外的是这是一个数组,执行上传时,三张图片产生的毫秒时间是相同的,导致结果你只能看到最后一张图片,因为他们的图片名称处理后是一样的,后来者覆盖了前面的,结果只剩一张了,那么在实际操作中,我们就有必要对它们再做其他处理,比如:在这里我在名称前面加上了循环变量i,那么三个名称就区分开了,结果当然就是我们想要的了。

struts2中使用kindeditor上传图片(包括jmagic压缩图片)

struts2中使用kindeditor上传图片(包括jmagic压缩图片)

@SuppressWarnings("serial")@ParentPackage("control-center")public class UploadContentImgAction extends BaseAction {private File up;private String upFileName;private String upContentType;private String fileDir = "uploads/articleContentImg";private String imgTitle;private String align;private int imgWidth;private int imgHeight;/*** kindeditor图片上传* @return* @throws Exception*/@Action("kindeditorImgUpload")public String kindeditorImgUpload() throws Exception {//只能传图片try {if(!validatePostfix(upFileName)) {return "error";}User user = (User)getSession().get("user");String fileRealDir = getServletContext().getRealPath(fileDir);File file = up;String fileRealName = createfilename(user.getUserId());String fileName = fileRealName + upFileName.substring(stIndexOf(".")).toLowerCase();File newFile = new File(fileRealDir, fileName);FileUtils.copyFile(file, newFile);//压缩图片ImageUtil.resize(newFile.getPath(), newFile.getPath(), 500);String id = "contentId";String url = "/" + fileDir + "/" + fileName;String border = "0";String result = "<script type='text/javascript'>parent.KE.plugin['image'].insert('" + id + "','" + url + "','" + imgTitle + "','" + imgHeight + "','" + imgHeight + "','" + border + "','" + align + "');</script>";getHttpServletResponse().getWriter().write(result);} catch (RuntimeException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}/*** 生成文件名: 当前时间+ 随机数+ 用户id*/private String createfilename(int userId) {StringBuilder result = new StringBuilder();// 得到本地的当前时间String now = DateUtil.getLongStrFromDate(new Date());// 在1000W 内随机生成一个数字int rand = new Random().nextInt(9999999);// 去掉- 去掉: 去掉空格后,返回result.append(now.replace("-", "").replace(":", "").replace(" ", "")).append("_").append(rand).append("_").append(userId);return result.toString();}/*** 验证后缀名应该从配置文件中获取*/public boolean validatePostfix(String filename) {// 定义可上传文件的类型List<String> fileTypes = new ArrayList<String>();// 图片fileTypes.add("jpg");fileTypes.add("jpeg");fileTypes.add("bmp");fileTypes.add("gif");fileTypes.add("png");// 得到文件尾数并进行小写转换String postfix = filename.substring(stIndexOf(".") + 1).toLowerCase();return fileTypes.contains(postfix) ? true : false;}public File getUp() {return up;}public void setUp(File up) {this.up = up;}public String getUpFileName() {return upFileName;}public void setUpFileName(String upFileName) { this.upFileName = upFileName;}public String getUpContentType() {return upContentType;}public void setUpContentType(String upContentType) { this.upContentType = upContentType;}public String getImgTitle() {return imgTitle;}public void setImgTitle(String imgTitle) {this.imgTitle = imgTitle;}public int getImgWidth() {return imgWidth;}public void setImgWidth(int imgWidth) {this.imgWidth = imgWidth;}public int getImgHeight() {return imgHeight;}public void setImgHeight(int imgHeight) {this.imgHeight = imgHeight;}public String getAlign() {return align;}public void setAlign(String align) {this.align = align;}}/*** @author**/public class ImageUtil {public final static int PHOTO_RATIO = 800; //缩放图片系数static{System.setProperty("jmagick.systemclassloader", "no");}/*** 图片水印** @param pressImg 水印图片* @param targetImg 目标图片* @param x 修正值默认在中间* @param y 修正值默认在中间* @param alpha 透明度*/public final static void pressImage(String pressImg, String targetImg,int x, int y, float alpha) {try {File img = new File(targetImg);Image src = ImageIO.read(img);int wideth = src.getWidth(null);int height = src.getHeight(null);BufferedImage image = new BufferedImage(wideth, height,BufferedImage.TYPE_INT_RGB);Graphics2D g = image.createGraphics();g.drawImage(src, 0, 0, wideth, height, null);// 水印文件Image src_biao = ImageIO.read(new File(pressImg));int wideth_biao = src_biao.getWidth(null);int height_biao = src_biao.getHeight(null);g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,alpha));g.drawImage(src_biao, (wideth - wideth_biao) / 2,(height - height_biao) / 2, wideth_biao, height_biao, null);// 水印文件结束g.dispose();ImageIO.write((BufferedImage) image, "jpg", img);} catch (Exception e) {e.printStackTrace();}}/*** 文字水印** @param pressText 水印文字* @param targetImg 目标图片* @param fontName 字体名称* @param fontStyle 字体样式* @param color 字体颜色* @param fontSize 字体大小* @param x 修正值* @param y 修正值* @param alpha 透明度*/public static void pressText(String pressText, String targetImg, String fontName, int fontStyle, Color color, int fontSize, int x,int y, float alpha) {try {File img = new File(targetImg);Image src = ImageIO.read(img);int width = src.getWidth(null);int height = src.getHeight(null);BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);Graphics2D g = image.createGraphics();g.drawImage(src, 0, 0, width, height, null);g.setColor(color);g.setFont(new Font(fontName, fontStyle, fontSize));g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_A TOP, alpha));g.drawString(pressText, (width - (getLength(pressText) * fontSize)) / 2 + x, (height - fontSize) / 2 + y);g.dispose();ImageIO.write((BufferedImage) image, "jpg", img);} catch (Exception e) {e.printStackTrace();}}/*** 缩放效果太差ps: Graphics下的还有AffineTransform下的* 缩放都是针对"图形"而不是"图像"的,所以处理后图片很不清晰* @param filePath 图片路径* @param height 高度* @param width 宽度* @param bb 比例不对时是否需要补白*/public static void resizeImgcale(String filePath, int height, int width, boolean bb) { try {double ratio = 0.0; // 缩放比例File f = new File(filePath);BufferedImage bi = ImageIO.read(f);Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);// 计算比例if ((bi.getHeight() > height) || (bi.getWidth() > width)) {if (bi.getHeight() > bi.getWidth()) {ratio = (new Integer(height)).doubleV alue() / bi.getHeight();} else {ratio = (new Integer(width)).doubleValue() / bi.getWidth();}AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);itemp = op.filter(bi, null);}if (bb) {BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);Graphics2D g = image.createGraphics();g.setColor(Color.white);g.fillRect(0, 0, width, height);if (width == itemp.getWidth(null))g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2,itemp.getWidth(null), itemp.getHeight(null),Color.white, null);elseg.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0,itemp.getWidth(null), itemp.getHeight(null),Color.white, null);g.dispose();itemp = image;}ImageIO.write((BufferedImage) itemp, "jpg", f);} catch (IOException e) {e.printStackTrace();}}/*** 计算字的长度** @param text* @return*/public static int getLength(String text) {int length = 0;for (int i = 0; i < text.length(); i++) {if (new String(text.charAt(i) + "").getBytes().length > 1) {length += 2;} else {length += 1;}}return length / 2;}/*** 压缩图片** @param imgsrc 源文件* @param imgdist 目标文件* @param widthdist 宽* @param heightdist 高*/public static void resizeImg(String imgsrc, String imgdist, int widthdist, int heightdist) { try {File srcfile = new File(imgsrc);if (!srcfile.exists()) {return;}Image src = javax.imageio.ImageIO.read(srcfile);BufferedImage tag = new BufferedImage(widthdist, heightdist, BufferedImage.TYPE_INT_RGB);/** SCALE_SMOOTH:尺寸平滑SCALE_AREA_A VERAGING:尺度区平均SCALE_FAST:尺度快速* SCALE_REPLICATE:尺度复制*/tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);FileOutputStream out = new FileOutputStream(imgdist);JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);encoder.encode(tag);out.close();} catch (IOException ex) {ex.printStackTrace();}}/*** 图片压缩* @param picFrom* @param picTo* @param widthdist* @param heightdist*/public static void resize(String picFrom, String picTo, int widthdist, int heightdist) { try {ImageInfo info = new ImageInfo(picFrom);MagickImage image = new MagickImage(new ImageInfo(picFrom));MagickImage scaled = image.scaleImage(widthdist, heightdist);// 小图片文件的大小.scaled.setFileName(picTo);scaled.writeImage(info);} catch (Exception ex) {ex.printStackTrace();}}public static void resize(String picFrom, String picTo, int ratio) throws Exception { BufferedImage bi = ImageIO.read(new File(picFrom));//原始图片属性int srcWidth = bi.getWidth();int srcHeight = bi.getHeight();//生成图片属性int newWidth = srcWidth;int newHeight = srcHeight;//如果超出最大宽或高就压缩if (srcWidth > ratio || newHeight > ratio) {//生成图片width, height计算if (srcWidth >= srcHeight) {if (srcWidth < ratio) {return;}newWidth = ratio;newHeight = (int)(ratio * srcHeight / srcWidth);} else {if (srcHeight < ratio) {return;}newHeight = ratio;newWidth = (int)(ratio * srcWidth / srcHeight);}}resize(picFrom, picTo, newWidth, newHeight);}public static void resize(String picFrom, String picTo) throws Exception {resize(picFrom, picTo, PHOTO_RATIO);}public static void main(String[] args) throws Exception {// resizeImg("d:/411766.jpg", "d:/411766_1.jpg", 800, 600);// resize("d:/test_4.jpg", "d:/test_4_2.jpg", 800);pressText("欢喜冤家", "d:/411766.jpg", "简体", Font.ITALIC, Color.black, 90, 40, 80, 0.5f);}}。

Struts2实现文件上传

Struts2实现文件上传

Struts2实现文件上传文件上传,说白了就是个文件复制的过程,文件复制需要什么呢,只需要有源文件和目标地址即可,·用main方法实现的文件复制代码如下:package cn.oracle.upload;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;public class FileUploadDemo {public static void main(String[] args) throws Exception{File input=new File(args[0]); 参数args[0]是你运行Java程序的时候输入的参数,下面有详细解释:if(!input.exists()){System.out.println("源文件不存在!");System.exit(0);}File output=new File(args[1]);if(!output.getParentFile().exists()){output.mkdirs();}OutputStream outputFile=new FileOutputStream(output);InputStream inputFile=new FileInputStream(input);byte data[]=new byte[1024];int temp=0;while((temp=inputFile.read(data))!=-1){outputFile.write(data, 0, temp);}outputFile.close();inputFile.close();}}例如上图中的Java 运行的程序类名称后面就是参数第一个是d:\1.txt 是一个参数args[0],d:\2.txt是第二个参数args[1]C:\Users\congz_000>java FileUploadDemo d:\1.txt d:\2.txt上面的代码就实现了文件的复制,其实在struts2之中的实现原理是一样的,也就是两个File对象,两个字节流对象,然后调用相应的方法执行的复制而已;在struts2之中实现的复制需要一个表单,将此表单的内容提交到一个action之中,然后struts负责参数的接受处理,赋给相应的变量,编写一个文件复制的方法即可完成文件上传;·给项目添加struts2开发支持,我们用自动配置的方式,用myeclipse帮我们完成,不需要做过多的配置,一路next即可;·新建一个upload.jsp页面<%@page language="java"import="java.util.*"pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort( )+path+"/";%><!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>文件上传</title></head><body><form action="FileUpload!upload.action"method="post"enctype="multipart/form-data"><input type="file"name="photo"id="photo"> 这个name属性一定要和action之中的File 类对象的名称一致;<input type="submit"value="上传"></form></body></html>·一个用来表示上传成功的页面<%@page language="java"import="java.util.*"pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort( )+path+"/";%><!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>文件上传</title></head><body><h1>上传成功</h1></body></html>·一个用来表示上传失败的页面<%@page language="java"import="java.util.*"pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort( )+path+"/";%><!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>文件上传</title></head><body><h2>上传失败!</h2></body></html>·编写相应的上传需要的action FileUploadActionpackage cn.oracle.action;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.util.UUID;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;@SuppressWarnings("serial")public class FileUploadAction extends ActionSupport { private File photo;private String photoFileName;public void setPhotoFileName(String photoFileName) { this.photoFileName = photoFileName;}public void setPhoto(File photo) {this.photo = photo;}public String upload(){System.out.println("************");String filePath =ServletActionContext.getServletContext().getRealPath("/upload")+ File.separator+ UUID.randomUUID()+ "."+ this.photoFileName.substring(this.photoFileName.lastIndexOf(".") + 1);if(this.saveFile(this.photo, filePath)){return"success";}return"failure";}public boolean saveFile(File input, String outputFilePath) { File output = new File(outputFilePath);if (!output.getParentFile().exists()) {output.mkdirs();}InputStream inputFile = null;try {inputFile = new FileInputStream(input);} catch (FileNotFoundException e) {e.printStackTrace();}OutputStream outputFile = null;try {outputFile = new FileOutputStream(output);} catch (FileNotFoundException e) {e.printStackTrace();}byte[] data = new byte[1024];int temp = 0;try {while ((temp = inputFile.read(data)) != -1) {outputFile.write(data, 0, temp);}if (inputFile != null) {inputFile.close();}if (outputFile != null) {outputFile.close();}return true;} catch (Exception e) {e.printStackTrace();}return false;}}·配置Struts.xml文件<?xml version="1.0"encoding="UTF-8"?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN""/dtds/struts-2.1.dtd"><struts><package name="main"namespace="/"extends="struts-default"><action name="FileUpload"class="cn.oracle.action.FileUploadAction"> <result name="success">/success.jsp</result><result name="failure">/failure.jsp</result></action></package></struts>·我们还需要配置一个Struts.properties的资源文件,在src之中,设置上传的限制和编码;struts.i18n.encoding=UTF-8struts.multipart.saveDir=/tempstruts.multipart.maxSize=2097152000·我们把项目部署到tomcat或者weblogic之中,按照你的连接访问,整个上传到此就完成了,这是个最简单的上传,没有做任何的修饰,有些上传做的很华丽的,那些都是div+css的功劳,如果你想要那种特效的话,需要研究下css 这个很不错的;。

java struts2入门学习实例--使用struts2快速实现多个文件上传

java struts2入门学习实例--使用struts2快速实现多个文件上传

一、错误提示信息配置昨天说到更改默认错误配置信息,我测试很多遍,一直都不对。

下面贴出来,待以后有好方法了再补充吧。

首先新建一个properties文件,这里命名为testupload.properties,内容为:rge=\u6587\u4EF6\u592A\u5927{0} "{1}" "{2}" {3}struts.messages.error.content.type.not.allowed=\u6587\u4EF6\u7C7B\u578B\u4E0D \u5141\u8BB8!{0} "{1}" "{2}" {3}struts.messages.error.file.extension.not.allowed=\u4E0D\u5141\u8BB8\u7684\u6269 \u5C55\u540D!{0} "{1}" "{2}" {3}这里将默认提示信息改为中文的。

upload.xml中内容如下:<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN""/dtds/struts-2.3.dtd"><struts><!-- 对上传文件总大小进行设置--><constant name="struts.multipart.maxSize"value="20971520"></constant><!-- 错误信息提示--><constant name="struts.custom.i18n.resources"value="testupload"/><package name="upload"extends="struts-default"><action name="UploadAction"class="action.UploadAction"method="up loadMethod"><result name="success"type="dispatcher">/WEB-INF/upload_success.jsp</result><result name="input"type="dispatcher">upload.jsp</result><!-- 对系统的拦截器进行设置--><interceptor-ref name="fileUpload"><!-- 对单个上传文件的大小进行设置,5M --><param name="maximumSize">5242880</param><!-- 对允许的文件扩展名进行设置,这里以英文逗号隔开--><param name="allowedExtensions">.txt,.xml</param><!-- 对允许的文件类型进行设置,这里以英文逗号进行隔开--><param name="allowedTypes">text/plain,text/xml</param> </interceptor-ref><!-- 显示引用默认的拦截器--><interceptor-ref name="defaultStack"></interceptor-ref></action></package></struts>二、多个文件上传只需要更改upload.jsp中的部分内容即可:<%@ page language="java"contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@ taglib uri="/struts-tags"prefix="s"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http: ///TR/html4/loose.dtd"> <html><head><meta http-equiv="Content-Type"content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><s:form action="UploadAction"enctype="multipart/form-data"method="POS T"><s:textfield label="上传用户"name="username"/><s:file label="上传文件"name="upload"/><s:file label="上传文件"name="upload"/><s:file label="上传文件"name="upload"/><s:submit value="提交"/></s:form></body></html>结果如下所示:也可以将UploadAction.java中的file改为数组类型的,如下所示:package action;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import javax.servlet.ServletContext;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;/*** @ClassName: UploadAction* @Description: 文件上传* @author: amosli* @email:amosli@* @date Jan 14, 2014 1:50:28 AM*/public class UploadAction extends ActionSupport {private static final long serialVersionUID = -8920466592471253212L;private String username;// 用户名private String[] uploadContentType;// 上传文件的类型,(Fileupload拦截器传入的参数)private File[] upload;// 上传的文件,(Fileupload拦截器传入的参数)private String[] uploadFileName;// 上传文件的真实文件名,(Fileupload拦截器传入的参数)public void setUsername(String username) {ername =username;}public String[] getUploadContentType() {return uploadContentType;}public void setUploadContentType(String[] uploadContentType) { this.uploadContentType =uploadContentType;}public File[] getUpload() {return upload;}public void setUpload(File[] upload) {this.upload =upload;}public String[] getUploadFileName() {return uploadFileName;}public void setUploadFileName(String[] uploadFileName) {this.uploadFileName =uploadFileName;}public String getUsername() {return username;}public String uploadMethod() throws Exception {ServletContext context =ServletActionContext.getServletContext();String real_path = context.getRealPath("/WEB-INF/upload/");for(int i = 0; i < upload.length; i++) {InputStream inputStream = new FileInputStream(upload[i]);OutputStream outputStream = new FileOutputStream(real_path + " /" +uploadFileName);byte[] b = new byte[1024];int len = 0;while((len = inputStream.read(b)) > 0) {outputStream.write(b, 0, len);}// 关闭流inputStream.close();outputStream.close();// 删除tmp文件,最好是用tyrcatch finally进行删除// upload[i].delete();}return SUCCESS;}}这里没有立马删除是想做个演示,查看一下缓存文件空间生成了几个。

Struts2实现文件上传和下载

Struts2实现文件上传和下载

一、Struts2实现文件上传1、添加必备jar包commons-logging-1.1.jarfreemarker-2.3.8.jarognl-2.6.11.jarstruts2-core-2.0.6.jarxwork-2.0.1.jarcommons-io-1.3.1.jarcommons-fileupload-1.2.jar2、jsp页面设置1)表单的提交方式必须为post2)表单标签必须添加属性enctype="multipart/form-data"3)表单元素file添加name属性3、Action类的编写1)根据表单元素file的name属性声明三个对应属性,一个是File类型,两个是字符串类型,并且三个属性名字固定,分别用于存储上传的文件,文件名及文件类型private file name属性名;private String name属性名FileName;private String name属性名ConentType;并提供对应的setter/getter方法2)在execute方法中编写代码Stringpath=ServletActionContext.getServletContext().getRealPath("/")+"/ images/"+headerFileName;FileUtils.copyFile(header, new File(path));3)如果一次上传多个文件,则需要保证所有上传控件的名字相同,在Action中声明三个集合或数组来接收上传上来的所有文件信息,并在execute方法中操作文件集合或数组即可for(int i=0;i<header.size();i++){File file=header.get(i);if(file!=null && file.exists()){Stringpath=ServletActionContext.getServletContext().getRealPath("/")+"/imag es/"+headerFileName.get(i);FileUtils.copyFile(file, new File(path));}}4、struts.xml配置文件1)注意,上传使用的action必须引用了fileupload拦截器,默认拦截器栈中已经包含了次拦截器了;只需注意如果引用了自定义拦截器,默认拦截器无效了;2)可以通过配置一些常量值,来控制上传文件的大小<constant name="struts.multipart.maxSize"value="1024000"></constant> 二、Struts2实现文件下载1、添加必备jar包commons-logging-1.1.jarfreemarker-2.3.8.jarognl-2.6.11.jarstruts2-core-2.0.6.jarxwork-2.0.1.jarcommons-io-1.3.1.jarcommons-fileupload-1.2.jar2、jsp页面设置<a href="download.action?fileName=${'权限练习.doc' }">权限需求文档</a><a href="download.action?fileName=${'Wind.jpg' }">风景画</a>提供超链接进行下载,点击时提交给action,并提供要下载的文件的名字及地址2、Action类的编写1)创建属性,接收提交过来的路径名及文件名,并提供getter/setter方法2)exectue方法直接return即可,无需编写任何代码3)编写下载方法public InputStream getDownloadFile()throws IOException{Stringpathname=ServletActionContext.getServletContext().getRealPath("/")+"/ images/"+fileName;HttpServletResponseresponse=ServletActionContext.getResponse();response.setContentType("application/x-msdownload");FileInputStream stream=new FileInputStream(new File(pathname));try {response.setHeader("Content-Disposition","attachment;filename="+newString(fileName.getBytes("gbk"),"iso-8859-1"));} catch (Exception e) {System.out.println("error:"+e.getMessage());}return stream;}注意此方法是自定义的,注意方法名字,必须符合驼峰命名法,以get开头即可3、struts.xml配置文件<action name="download"class="cn.mystruts.action.DownloadAction"> <result name="ok"type="stream"><param name="inputName">downloadFile</param><param name="bufferSize">1024</param></result></action>注意:1、参数inputName给的值是所编写的下载方法的名字去掉get,并要求符合驼峰命名法2、在tomcat/conf/server.xml中修改默认端口号的connector节点后添加属性URIEncoding=”UTF-8”。

Struts2中多文件上传

Struts2中多文件上传

一、上传页面:<%@ page language="java" contentType="text/html; charset=GBK"%><%@taglib prefix="s" uri="/struts-tags"%><html xmlns="/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=GBK" /><title>使用数组上传多个文件</title></head><body><s:fielderror/><form action="upload.action" method="post" enctype="multipart/form-data">文件标题:<input type="text" name="title" /><br>选择第一个文件:<input type="file" name="upload" /><br>选择第二个文件:<input type="file" name="upload" /><br>选择第三个文件:<input type="file" name="upload" /><br><input value="上传" type="submit" /></form></body></html>二、上传成功页面:<%@ page language="java" contentType="text/html; charset=GBK"%><%@taglib prefix="s" uri="/struts-tags"%><html><head><title>上传成功</title></head><body>上传成功!<br>文件标题:<s:property value=" + title"/><br>第一个文件为:<img src="<s:property value="'upload/' + uploadFileName[0]"/>"/><br>第二个文件为:<img src="<s:property value="'upload/' + uploadFileName[1]"/>"/><br> 第三个文件为:<img src="<s:property value="'upload/' + uploadFileName[2]"/>"/><br></body></html>三、动作类package lee;import com.opensymphony.xwork2.Action;import org.apache.struts2.ServletActionContext;import java.io.File;import java.io.*;import com.opensymphony.xwork2.ActionSupport;/*** @author yeeku.H.lee kongyeeku@* @version 1.0* Copyright (C), 2005-2008, yeeku.H.Lee* This program is protected by copyright laws.* Program Name:* Date:*/public class UploadAction extends ActionSupport{private String title;private File[] upload;private String[] uploadContentType;private String[] uploadFileName;//接受依赖注入的属性private String savePath;//接受依赖注入的方法public void setSavePath(String value){this.savePath = value;}private String getSavePath() throws Exception{returnServletActionContext.getRequest().getRealPath(savePath);}public void setTitle(String title) {this.title = title;}public void setUpload(File[] upload) {this.upload = upload;}public void setUploadContentType(String[] uploadContentType) { this.uploadContentType = uploadContentType;}public void setUploadFileName(String[] uploadFileName) {this.uploadFileName = uploadFileName;}public String getTitle() {return (this.title);}public File[] getUpload() {return (this.upload);}public String[] getUploadContentType() {return (this.uploadContentType);}public String[] getUploadFileName() {return (this.uploadFileName);}@Overridepublic String execute() throws Exception{File[] files = getUpload();for (int i = 0 ; i < files.length ; i++){//以服务器的文件保存地址和原文件名建立上传文件输出流FileOutputStream fos = newFileOutputStream(getSavePath() + "\\" + getUploadFileName()[i]);FileInputStream fis = newFileInputStream(files[i]);byte[] buffer = new byte[1024];int len = 0;while ((len = fis.read(buffer)) > 0){fos.write(buffer , 0 , len);}}fos.close();// 注意:流应当关闭。

Struts2的文件上传

Struts2的文件上传

显示上传成功页面 配置文件
多个文件上传配置
配置struts.xml,与单个文件上传配置类似
<action name="multiFileUpload" class="it.MultiFileUploadAction"> <!-- 动态设置Action中的savePath属性的值 --> <interceptor-ref name="fileUpload"> <!-- 配置允许上传的文件类型,多个用","分隔 --> <param name="allowedTypes">image/bmp,image/png,image/gif, image/jpeg,image/jpg,image/x-png,image/pjpeg</param> <param name="maximumSize">10240000</param> </interceptor-ref> <interceptor-ref name="defaultStack" /> <result name="input">/multifileupload.jsp</result> <param name="savePath">/upload</param> <result name="success">/success.jsp</result>
}
5
单个文件上传
使用Struts2框架实现单个文件上传,步骤

通过代码实例跟我学Struts2框架从入门到精通——在Struts2框架中实现Web文件上传的相关应用技术

通过代码实例跟我学Struts2框架从入门到精通——在Struts2框架中实现Web文件上传的相关应用技术
在Struts2框架中实现Web文件上传的 相关应用技术
在Struts2框架中实现Web文件上传的 相关应用技术
在本讲您能了解如下知识点 (The Emphases in Teaching Materials ) 文件上传的实现原理 Jakarta的Common-FileUpload组件 Struts2中的文件上传的实现及示例 限制上传文件的类型及大小 在Struts2中实现多文件上传 在Struts2中文件下载实现及示例
( 2 ) Struts2 默认使用的是 Jakarta 的 Common-FileUpload 框架来上传文件
(3)上传文件的基本实现过程
Struts2 是通过 Commons FileUpload 文件上传,而 Commons FileUpload 通过 将 HTTP 的数 据 保存到 临 时文件 夹 ,然后 Struts2使用fileUpload拦截器将文件绑定到Action的实例 中。 从而就能够在 Action 类中以本地文件 IO 操作方式来操作通 过浏览器上传的各种形式的文件。
2、Jakarta的Common-FileUpload组件
Hale Waihona Puke 3、Struts2中的文件上传的实现 (1)Struts2更进一步简化了文件上传的功能实现
Struts2 并未提供自己的请求解析器,也就是 Struts2 不会 自己去处理multipart/form-data的请求,它需要调用其他 请求解析器,将HTTP请求中的表单域解析出来。 但Struts2在原有的上传解析器基础上做了进一步封装,更 进一步简化了Web 文件上传的功能实现。
(7)部署并执行本struts2FileUpload.jsp( http://localhost:8080/Struts2Web/fileUpload.jsp)

FileUpload——在Struts2中上传文件

FileUpload——在Struts2中上传文件

FileUpload——在Struts2中上传文件大家可能注意一个问题很久了,在现在我们使用的Struts2版本中有一个commons-fileupload.jar,之前我们就提到,这个jar 包主要是对文件上传的支持,看来Struts2认为在一个应用中文件的上传是个必要。

本章节我们就一起来看看怎样在Struts2中实现文件上传,配置及基本做法。

配置在我们现在使用的版本中我们不需要什么配置,除非你想做点特别的事情。

这里我们不讨论Struts2其他版本的文件上传问题。

基本做法OK,我们看到要实现文件上传基本上不需要额外的配置,比如说什么上传插件啦,相信我们的Struts2在这方面的使用时非常方便的。

现在我们抛去Struts2,来想一想我们平时或以前在编写应用时怎样来实现文件上传的呢。

要关心文件流的读写问题,存放位置,文件的打开与关闭,请求方式等等。

带着我们平时编码的这些问题来看看Struts2中的解决方式。

Step1: new一个jsp页面作为文件上传的页面<%@page language="java"contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@taglib uri="/struts-tags"prefix="s"%><!DOCTYPE html PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type"content="text/html;charset=UTF-8"><title>FileUpload Page</title></head><body><h2>Please select a file </h2><s:form action="doUpload"enctype="multipart/form-data" method="post"><s:file name="upload"label="Upload File"/><s:textfield name="caption"label="Caption"/><s:submit></s:submit></s:form></body></html>这里你或许注意到了,我使用了<X:file>标签,作用就是在客户端产生一个文件域用来上传文件,然后我们为文件添加了一个标题(catpion)。

依据SSH IO流 上传文件流程

依据SSH  IO流 上传文件流程

Struts2+Spring+Hibernate上传文件前段时间,我用struts2.1.6、spring2.5、hibernate3.3做了一个文件上传的demo。

上传是通过struts2自带的组件Commons FileUpload文件上传的。

上传需要的jar包:commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar。

首先了解一下文件上传的原理:表单元素的enctype属性指定的是表单数据的编码方式,该属性有3个值:a 、 application/x-www-form-urlencoded:这是默认编码方式,它只处理表单域里的value属性值,采用这种编码方式的表单会将表单域的值处理成URL编码方式。

b 、 multipart/form-data:这种编码方式的表单会以二进制流的方式来处理表单数据,这种编码方式会把文件域指定文件的内容也封装到请求参数里。

c、 text/plain:这种方式主要适用于直接通过表单发送邮件的方式。

上传文件主要是通过读写二进制流进行操作的。

配置很简单,相信网上有很多这方面的资料,我就不再叙述了(最后面引用了网友的对struts2文件上传的配置)。

主要说明1点:因为spring的bean 默认是单态singleton的。

这样导致一个问题:就是当我们如果上传了一个不允许的类型文件或超出大小范围的文件,之后再上传正常的文件也上传不了。

这时候需要把bean设置为非单态模式:Java代码<!-- 上传action --><bean id="uploadAction" class="com.action.upload.UploadAction"scope="prototype"><property name="busiWlphotodirService"ref="busiWlphotodirService"></property></bean>1. 文件上传的原理:表单元素的enctype属性指定的是表单数据的编码方式,该属性有3个值:1) application/x-www-form-urlencoded:这是默认编码方式,它只处理表单域里的value属性值,采用这种编码方式的表单会将表单域的值处理成URL编码方式。

struts2实现文件上传(单个+多个文件上传)

struts2实现文件上传(单个+多个文件上传)

Struts2实现的文件上传功能一,单个文件上传 (2)Jsp页面 (2)Action层代码 (2)Struts.xml配置文件中代码 (4)上传成功跳转页面代码 (5)二,多文件上传 (5)Jsp页面 (5)Action层代码 (6)Struts配置文件(与单个一样) (8)上传成功后显示页面 (8)文件上传,类型的拦截,具体请看action的配置 (9)一,单个文件上传Jsp页面<!-- 错误处理,如果不是指定的文件报错,指定的文件类型在struts.xml文件中--><s:fielderror/><s:form action="fileUpload"method="post" enctype="multipart/form-data"><!—这个myFile与后面action里面私有变量对应--><s:file name="myFile"label="image File"/><s:submit/><s:reset/></s:form>Action层代码public class FileFloadAction extends ActionSupport{private static final int BUFFER_SIZE = 16 * 1024;// 与jsp页面<s:file name="myFile"/>的name对应private File myFile;// 通过myFile自动传递过来ContentType,起名为file的名字+ContentTypeprivate String myFileContentType;// 文件的名字,与上ContentType类似,起名为file的名字+FileName private String myFileFileName;// 图片的名字private String imageFileName;****************************************************此处生成get,set方法****************************************************//得到文件的名字与类型,并返回private static String getExtention(String myFileFileName) {int pos = stIndexOf("\\");return myFileFileName.substring(pos + 1);//实现文件的拷贝private static void copy(File src, File dst){try{InputStream in = null;OutputStream out = null;try{in = new BufferedInputStream(new FileInputStream(src),BUFFER_SIZE);out = new BufferedOutputStream(new FileOutputStream(dst),BUFFER_SIZE);byte[] buffer = new byte[BUFFER_SIZE];//修正后的copyfor (int byteRead = 0; (byteRead =in.read(buffer)) > 0;){out.write(buffer, 0, byteRead);}}finally{if (null != in)in.close();if (null != out)out.close();}}catch (Exception e){e.printStackTrace();}}public String fileFload()//名字可以取时间+类型(不会重复)// imageFileName = new Date().getTime() + getExtention(fileName);//得到image的名字及类型imageFileName = getExtention(myFileFileName);//得到将要上传的目的地的路径String totalPath =ServletActionContext.getServletContext().getRealPath("/img");//在目的地创建一个文件File imageFile = new File(totalPath + "/" + imageFileName);//把要上传的文件复制到目的地文件中去copy(myFile, imageFile);return SUCCESS;}}Struts.xml配置文件中代码//文件上传<action name="fileUpload"class="com.forum.action.FileFloadAction"method="fileFload"> <interceptor-ref name ="fileUpload"><param name ="allowedTypes">image/bmp,image/png,image/gif,image/jpeg</param></interceptor-ref><interceptor-ref name ="defaultStack"/><result name="input">/fileUpload.jsp</result><resultname="success">/fileUploadSuccess.jsp</result></action>上传成功跳转页面代码<img alt="myfile" src="img/<s:propertyvalue="imageFileName"/>">二,多文件上传Jsp页面<!-- 错误处理,如果不是指定的文件报错,指定的文件类型在struts.xml文件中 --><s:fielderror/><s:form action="multipleFilesUpload"method="POST"enctype="multipart/form-data"><s:file label="File(1)"name="upload"/><s:file label="File(2)"name="upload"/><s:file label="FIle(3)"name="upload"/><s:submit/></s:form>Action层代码public class MultipleFilesUploadAction extends ActionSupport {private static final int BUFFER_SIZE = 16*1024;private List<File> uploads = new ArrayList<File>();private List<String> uploadFileNames = newArrayList<String>();private List<String> uploadContentTypes = newArrayList<String>();private List<String> imagesName = new ArrayList<String>(); ****************************************************此处生成get,set方法**************************************************** private static List<String> getExtention(List<String> filesName){List<String> lastNames = new ArrayList<String>();for(Iterator<String> iter =filesName.iterator();iter.hasNext(); ){int pos = stIndexOf("\\");lastNames.add(iter.next().substring(pos + 1));}return lastNames;}private static void copy(List<File> src, List<File> dst) {try{InputStream in = null;OutputStream out = null;try{for (int i = 0;i<src.size();i++){in = new BufferedInputStream(new FileInputStream(src.get(i)),BUFFER_SIZE);out = new BufferedOutputStream(new FileOutputStream(dst.get(i)),BUFFER_SIZE);byte[] buffer = new byte[BUFFER_SIZE];// 修正后的copyfor (int byteRead = 0; (byteRead =in.read(buffer)) > 0;){out.write(buffer, 0, byteRead);}}}finally{if (null != in)in.close();if (null != out)out.close();}}catch (Exception e){e.printStackTrace();}}public String multipleFilesUpload(){//得到文件的名字imagesName=getExtention(uploadFileNames);//将要存放文件路径折文件夹String totalPath = ServletActionContext.getServletContext() .getRealPath("/img");//生成文件List<File> imagesFile = new ArrayList<File>();for(Iterator<String> iter =imagesName.iterator();iter.hasNext();){imagesFile.add(new File(totalPath + "/" +iter.next()));}copy(uploads, imagesFile);return SUCCESS;}}Struts配置文件(与单个一样)<action name="multipleFilesUpload"class="com.forum.action.MultipleFilesUploadAction"method="multipleFilesUpload"><interceptor-ref name ="fileUpload"><param name ="allowedTypes">image/bmp,image/png,image/gif,image/jpeg</param></interceptor-ref><interceptor-ref name ="defaultStack"/><result name="input">/fileUpload.jsp</result><result name="success">/fileUploadSuccess.jsp</result> </action>上传成功后显示页面<s:iterator value="imagesName"><img alt="<s:property/>"src="img/<s:property/>"width="320px"height="240px"> </s:iterator>提示:上传的文件夹一定要在上传之前创建完成,本例是用的img文件夹,在webContext下面。

Struts2与xheditor配置

Struts2与xheditor配置

Struts2+xheditor使用1、添加页面InfoAdd.jsp<form action="infoEdit/infoAction!addInfo.action"method="post"> <input type="submit"value="登录"></form>2、添加action类InfoAction.javapublic String addInfo() throws Exception {System.out.println("success");return"success";}3、配置struts.xml<package name="info"extends="struts-default"namespace="/infoEdit"> <action name="infoAction"class="Aciton"><result name="success">/infoEdit/infoList.jsp</result><result name="fail">/infoEdit/error.jsp</result> </action></package>Xheditor添加1、拷贝js到webroot2、使用xheditor的页面中添加js的引用<base href="<%=basePath%>"><script src="<%=basePath%>scripts/xheditor/jquery-1.4.2.min.js"type="text/javascript"></script><script src="<%=basePath%>scripts/xheditor/xheditor-zh-cn.min.js"type="text/javascript"></script><script type="text/javascript">$(document).ready(function(){//初始化xhEditor编辑器插件$('#xh_editor').xheditor({tools:'simple',skin:'default',upMultiple:false,upImgUrl: "<%=basePath %>servlet/UploadFileServlet",upImgExt: "jpg,jpeg,gif,bmp,png",upLinkUrl: "<%=basePath %>servlet/UploadFileServlet",upLinkExt:"doc,txt,pdf,xls,ppt,rar,zip",onUpload:insertUpload});//xbhEditor编辑器图片上传回调函数function insertUpload(msg) {var _msg = msg.toString();var _picture_name = _msg.substring(_stIndexOf("/")+1);var _picture_path = Substring(_msg);var _str = "<input type='checkbox' name='_pictures'value='"+_picture_path+"' checked='checked' onclick='returnfalse'/><label>"+_picture_name+"</label><br/>";$("#xh_editor").append(_msg);$("#uploadList").append(_str);}//处理服务器返回到回调函数的字符串内容,格式是JSON的数据格式.function Substring(s){returns.substring(s.substring(0,stIndexOf("/")).lastIndexOf("/"),s.length);}});</script>3、xheditor页面信息内容:<textarea id="xh_editor"name="contents"rows="25"style="width: 100%; border: 1px"></textarea>还有几个jar添加上传文件servlet配置web.xml<servlet ><servlet-name >XhEditor </servlet-name ><servlet-class >com.xheditor.servlet.UploadFileServlet </servlet-class ></servlet ><servlet-mapping ><servlet-name >XhEditor </servlet-name ><url-pattern >/servlet/UploadFileServlet </url-pattern ></servlet-mapping >添加数据库1、 powerdesigner 设计表infoid title contents bigint varchar(50)text <pk>生成自增字段drop table if exists info;/*==============================================================*//* Table: info *//*==============================================================*/create table info(id bigint not null auto_increment,title varchar(50) not null,contents text not null,primary key (id));2、info类package info;public class Info {private String title,contents;public String getTitle() {return title;}public void setTitle(String title) {this.title = title; }public String getContents() {return contents;}public void setContents(String contents) {this.contents = contents;}}3、InfoDao类package info;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;public class InfoDao {public int addInfo(Info info) throws Exception{// 第一步:加载驱动(驱动jar包必须加入classpath中)Class.forName("com.mysql.jdbc.Driver");// 第二步:建立连接(根据实际情况替换数据库的主机地址、端口号、数据库明、登录名、密码)Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=utf-8", "root", "ailab3313");System.out.println("当前连接到的数据库=" + conn.getCatalog());// 查看当前连接到的数据库名// 第三步:创建Statement对象Statement stmt = conn.createStatement();// 只读的结果集// 第四步:执行操作(增删改查)String sql ="insert infovalues(null,'"+info.getTitle()+"','"+info.getContents()+"')";System.out.println(sql);int line = stmt.executeUpdate(sql);//int rs = stmt.executeUpdate("insert into student value(5,2,'3')");// 第五步:关闭连接conn.close();return line; }}4、InfoAction中public String addInfo() throws Exception {System.out.println(title);System.out.println(contents);Info info = new Info();info.setTitle(title);info.setContents(contents);InfoDao infoDao = new InfoDao();int flag = infoDao.addInfo(info);if (flag==1)return"success";elsereturn"fail"; }。

jspstruts1struts2上传文件

jspstruts1struts2上传文件

一.在JSP环境中利用Commons-fileupload组件实现文件上传1.页面upload.jsp清单如下:Java代码1.<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>2.3.<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML4.01 Transitional//EN">4.<html>5. <head>6. <title>The FileUpload Demo</title>7. </head>8.9. <body>10. <form action="UploadFile" method="post" enctype="multipart/form-data">11. <p><input type="text" name="fileinfo" value="">文件介绍</p>12. <p><input type="file" name="myfile" value="阅读文件"></p>13. <p><input type="submit" value="上传"></p>14. </form>15. </body>16.</html>注意:在上传表单中,既有一般文本域也有文件上传域2.FileUplaodServlet.java清单如下:Java代码1.package org.chris.fileupload;2.3.import java.io.File;4.import java.io.IOException;5.import java.util.Iterator;6.import java.util.List;7.8.import javax.servlet.ServletException;9.import javax.servlet.http.*;10.11.import org.apachemons.fileupload.FileItem;12.import org.apachemons.fileupload.FileItemFactory;13.import org.apachemons.fileupload.disk.DiskFileItemFactory;14.import org.apachemons.fileupload.servlet.ServletFileUpload;15.16.public class FileUplaodServlet extends HttpServlet {17.18. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {19. doPost(request, response);20. }21.22. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {23.24. request.setCharacterEncoding("UTF-8");25.26. //文件的上传部份27. boolean isMultipart = ServletFileUpload.isMultipartContent(request);28.29. if(isMultipart)30. {31. try {32. FileItemFactory factory = new DiskFileItemFactory();33. ServletFileUpload fileload = new ServletFileUpload(factory);34.35.// 设置最大文件尺寸,那个地址是4MB36. fileload.setSizeMax(4194304);37. List<FileItem> files = fileload.parseRequest(request);38. Iterator<FileItem> iterator = files.iterator();39. while(iterator.hasNext())40. {41. FileItem item = iterator.next();42. if(item.isFormField())43. {44. String name = item.getFieldName();45. String value = item.getString();46. System.out.println("表单域名为: " + name + "值为: " + value);47. }else48. {49. //取得取得文件名,此文件名包括途径50. String filename = item.getName();51. if(filename != null)52. {53. File file = new File(filename);54. //若是此文件存在55. if(file.exists()){56. File filetoserver = new File("d:\\upload\\",file.getName());57. item.write(filetoserver);58. System.out.println("文件 " + filetoserver.getName() + " 上传成功!!");59. }60. }61. }62. }63. } catch (Exception e) {64. System.out.println(e.getStackTrace());65. }66. }67. }68.}3.web.xml清单如下:Java代码1.<?xml version="1.0" encoding="UTF-8"?>2.<web-app version="2.4"3. xmlns="java.sun/xml/ns/j2ee"4. xmlns:xsi="/2001/XMLSchema-instance"5. xsi:schemaLocation="java.sun/xml/ns/j2ee6. java.sun/xml/ns/j2ee/web-app_2_4.xsd">7.8. <servlet>9. <servlet-name>UploadFileServlet</servlet-name>10. <servlet-class>11. org.chris.fileupload.FileUplaodServlet12. </servlet-class>13. </servlet>14.15. <servlet-mapping>16. <servlet-name>UploadFileServlet</servlet-name>17. <url-pattern>/UploadFile</url-pattern>18. </servlet-mapping>19.20. <welcome-file-list>21. <welcome-file>/Index.jsp</welcome-file>22. </welcome-file-list>23.24.</web-app>二.在strut1.2中实现1.上传页面file.jsp 清单如下:Java代码1.<%@ page language="java" pageEncoding="ISO-8859-1"%>2.<%@ taglib uri="/struts/tags-bean" prefix="bean"%>3.<%@ taglib uri="/struts/tags-html" prefix="html"%>4.5.<html>6. <head>7. <title>JSP for FileForm form</title>8. </head>9. <body>10. <html:form action="/file" enctype="multipart/form-data">11. <html:file property="file1"></html:file>12. <html:submit/><html:cancel/>13. </html:form>14. </body>15.</html>2.FileAtion.java的清单如下:Java代码1./*2. * Generated by MyEclipse Struts3. * Template path: templates/java/JavaClass.vtl4. */5.package action;6.7.import java.io.*;8.9.import javax.servlet.http.HttpServletRequest;10.import javax.servlet.http.HttpServletResponse;11.import org.apache.struts.action.Action;12.import org.apache.struts.action.ActionForm;13.import org.apache.struts.action.ActionForward;14.import org.apache.struts.action.ActionMapping;15.import org.apache.struts.upload.FormFile;16.17.import form.FileForm;18.19./**20. * @author Chris21. * Creation date: 6-27-202022. *23. * XDoclet definition:24. * @struts.action path="/file" name="fileForm" input="/file.jsp"25. */26.public class FileAction extends Action {27. /*28. * Generated Methods29. */30.31. /**32. * Method execute33. * @param mapping34. * @param form35. * @param request36. * @param response37. * @return ActionForward38. */39. public ActionForward execute(ActionMapping mapping, ActionForm form,40. HttpServletRequest request, HttpServletResponse response) {41. FileForm fileForm = (FileForm) form;42. FormFile file1=fileForm.getFile1();43. if(file1!=null){44. //上传途径45. String dir=request.getSession(true).getServletContext().getRealPath("/upload");46. OutputStream fos=null;47. try {48. fos=new FileOutputStream(dir+"/"+file1.getFileName());49. fos.write(file1.getFileData(),0,file1.getFileSize());50. fos.flush();51. } catch (Exception e) {52. // TODO Auto-generated catch block53. e.printStackTrace();54. }finally{55. try{56. fos.close();57. }catch(Exception e){}58. }59. }60. //页面跳转61. return mapping.findForward("success");62. }63.}3.FileForm.java的清单如下:Java代码1.package form;2.3.import javax.servlet.http.HttpServletRequest;4.import org.apache.struts.action.ActionErrors;5.import org.apache.struts.action.ActionForm;6.import org.apache.struts.action.ActionMapping;7.import org.apache.struts.upload.FormFile;8.9./**10. * @author Chris11. * Creation date: 6-27-202012. *13. * XDoclet definition:14. * @struts.form name="fileForm"15. */16.public class FileForm extends ActionForm {17. /*18. * Generated Methods19. */20. private FormFile file1;21. /**22. * Method validate23. * @param mapping24. * @param request25. * @return ActionErrors26. */27. public ActionErrors validate(ActionMapping mapping,28. HttpServletRequest request) {29. // TODO Auto-generated method stub30. return null;31. }32.33. /**34. * Method reset35. * @param mapping36. * @param request37. */38. public void reset(ActionMapping mapping, HttpServletRequest request) {39. // TODO Auto-generated method stub40. }41.42. public FormFile getFile1() {43. return file1;44. }45.46. public void setFile1(FormFile file1) {47. this.file1 = file1;48. }49.}4.struts-config.xml的清单如下:Java代码1.<?xml version="1.0" encoding="UTF-8"?>2.<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "/d tds/struts-config_1_2.dtd">3.4.<struts-config>5. <data-sources />6. <form-beans >7. <form-bean name="fileForm" type="form.FileForm" />8.9. </form-beans>10.11. <global-exceptions />12. <global-forwards />13. <action-mappings >14. <action15. attribute="fileForm"16. input="/file.jsp"17. name="fileForm"18. path="/file"19. type="action.FileAction"20. validate="false">21. <forward name="success" path="/file.jsp"></forward>22. </action>23.24. </action-mappings>25.26. <message-resources parameter="ApplicationResources" />27.</struts-config>5.web.xml代码清单如下:Java代码1.<?xml version="1.0" encoding="UTF-8"?>2.<web-app xmlns="java.sun/xml/ns/j2ee" xmlns:xsi="w/2001/XMLSchema-instance" version="2.4" xsi:schemaLocatio n="java.sun/xml/ns/j2ee java.sun/xml/ns/j2ee/web-app_2_4.xsd">3. <servlet>4. <servlet-name>action</servlet-name>5. <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>6. <init-param>7. <param-name>config</param-name>8. <param-value>/WEB-INF/struts-config.xml</param-value>9. </init-param>10. <init-param>11. <param-name>debug</param-name>12. <param-value>3</param-value>13. </init-param>14. <init-param>15. <param-name>detail</param-name>16. <param-value>3</param-value>17. </init-param>18. <load-on-startup>0</load-on-startup>19. </servlet>20. <servlet-mapping>21. <servlet-name>action</servlet-name>22. <url-pattern>*.do</url-pattern>23. </servlet-mapping>24.</web-app>三.在struts2中实现(以图片上传为例)1.FileUpload.jsp代码清单如下:Java代码1.<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>2.<%@ taglib prefix="s" uri="/struts-tags" %>3.<html>4. <head>5. <title>The FileUplaodDemo In Struts2</title>6. </head>7.8. <body>9. <s:form action="fileUpload.action" method="POST" enctype="multipart/form-data">10. <s:file name="myFile" label="MyFile" ></s:file>11. <s:textfield name="caption" label="Caption"></s:textfield>12. <s:submit label="提交"></s:submit>13. </s:form>14. </body>15.</html>2.ShowUpload.jsp的功能清单如下:Java代码1.<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>2.<%@ taglib prefix="s" uri="/struts-tags" %>3.<html>4. <head>5. <title>ShowUpload</title>6. </head>7.8. <body>9. <div style ="padding: 3px; border: solid 1px #cccccc; text-align: center" >10. <img src ='UploadImages/<s:property value ="imageFileName"/> '/>11. <br />12. <s:property value ="caption"/>13. </div >14. </body>15.</html>3.FileUploadAction.java的代码清单如下:Java代码1.package com.chris;2.3.import java.io.*;4.import java.util.Date;5.6.import org.apache.struts2.ServletActionContext;7.8.9.import com.opensymphony.xwork2.ActionSupport;10.11.public class FileUploadAction extends ActionSupport{12.13. private static final long serialVersionUID = 572146812454l;14. private static final int BUFFER_SIZE = 16 * 1024 ;15.16. //注意,文件上传时<s:file/>同时与myFile,myFileContentType,myFileFileName绑定17. //因此同时要提供myFileContentType,myFileFileName的set方式18.19. private File myFile; //上传文件20. private String contentType;//上传文件类型21. private String fileName; //上传文件名22. private String imageFileName;23. private String caption;//文件说明,与页面属性绑定24.25. public void setMyFileContentType(String contentType) {26. System.out.println("contentType : " + contentType);27. this .contentType = contentType;28. }29.30. public void setMyFileFileName(String fileName) {31. System.out.println("FileName : " + fileName);32. this .fileName = fileName;33. }34.35. public void setMyFile(File myFile) {36. this .myFile = myFile;37. }38.39. public String getImageFileName() {40. return imageFileName;41. }42.43. public String getCaption() {44. return caption;45. }46.47. public void setCaption(String caption) {48. this .caption = caption;49. }50.51. private static void copy(File src, File dst) {52. try {53. InputStream in = null ;54. OutputStream out = null ;55. try {56. in = new BufferedInputStream( new FileInputStream(src), BUFFER_SIZE);57. out = new BufferedOutputStream( new FileOutputStream(dst), BUFFER_SIZE);58. byte [] buffer = new byte [BUFFER_SIZE];59. while (in.read(buffer) > 0 ) {60. out.write(buffer);61. }62. } finally {63. if ( null != in) {64. in.close();65. }66. if ( null != out) {67. out.close();68. }69. }70. } catch (Exception e) {71. e.printStackTrace();72. }73. }74.75. private static String getExtention(String fileName) {76. int pos = stIndexOf(".");77. return fileName.substring(pos);78. }79.80.@Override81. public String execute() {82. imageFileName = new Date().getTime() + getExtention(fileName);83. File imageFile = new File(ServletActionContext.getServletContext().getRealPath("/UploadImages" ) + "/" + imageFileN ame);84. copy(myFile, imageFile);85. return SUCCESS;86. }87.}注:现在仅为方便实现Action因此继承ActionSupport,并Overrider execute()方式在struts2中任何一个POJO都能够作为Action4.struts.xml清单如下:Java代码1.<?xml version="1.0" encoding="UTF-8" ?>2.<!DOCTYPE struts PUBLIC3. "-//Apache Software Foundation//DTD Struts Configuration2.0//EN"4. "/dtds/struts-2.0.dtd">5.<struts>6. <package name="example" namespace="/" extends="struts-default">7. <action name="fileUpload" class="com.chris.FileUploadAction">8. <interceptor-ref name="fileUploadStack"/>9. <result>/ShowUpload.jsp</result>10. </action>11. </package>12.</struts>5.web.xml清单如下:Java代码1.<?xml version="1.0" encoding="UTF-8"?>2.<web-app version="2.4"3. xmlns="java.sun/xml/ns/j2ee"4. xmlns:xsi="/2001/XMLSchema-instance"5. xsi:schemaLocation="java.sun/xml/ns/j2ee6. java.sun/xml/ns/j2ee/web-app_2_4.xsd">7. <filter >8. <filter-name > struts-cleanup </filter-name >9. <filter-class >10. org.apache.struts2.dispatcher.ActionContextCleanUp11. </filter-class >12. </filter >13. <filter-mapping >14. <filter-name > struts-cleanup </filter-name >15. <url-pattern > /* </url-pattern >16. </filter-mapping >17.18. <filter>19. <filter-name>struts2</filter-name>20. <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>21. </filter>22. <filter-mapping>23. <filter-name>struts2</filter-name>24. <url-pattern>/*</url-pattern>25. </filter-mapping>26. <welcome-file-list>27. <welcome-file>Index.jsp</welcome-file>28. </welcome-file-list>29.30.</web-app>。

基于Vue2实现移动端图片上传、压缩、拖拽排序、拖拽删除功能

基于Vue2实现移动端图片上传、压缩、拖拽排序、拖拽删除功能

基于Vue2实现移动端图⽚上传、压缩、拖拽排序、拖拽删除功能⽬录图⽚上传图⽚压缩拖拽排序、拖拽删除⽤Vue2实现移动端图⽚上传、压缩、拖拽排序、拖拽删除功能图⽚上传图⽚压缩拖拽排序、拖拽删除之前在公司开发过⼀段时间的移动端H5页⾯,有个功能就是要上传图⽚+压缩。

参考了⼀下⽹上的⽅法,外加⾃⼰摸索的过程,最终实现了这个功能。

后⾯在家闲的时候⼜加多了个长按选中图⽚,并且可以拖拽排序、拖拽到指定位置删除的功能。

github地址:下⾯直接进⼊正题:图⽚上传图⽚上传⽤的是HTML的input标签实现的。

核⼼就是把获取到的⽂件通过FileReader转换成图⽚,代码如下:<input type="file" accept="image/*" capture="camera" @change="selectFile">selectFile(event:any){this.showAlert = falseif (event.target.files && event.target.files.length > 0) {this.isLoading = truelet file:any = event.target.files[0]let fr:any = new FileReader()fr.readAsDataURL(file)fr.onload = (imgObj:any) => {let img:any = new Image()img.src = imgObj.target.resultimg.onload = (e:any) => {// 这⾥就可以获取到上传的图⽚了})}}}}图⽚压缩图⽚压缩⽤的是canvas重绘的⽅法实现的,具体代码如下:// 省略上⾯的代码fr.onload = (imgObj:any) => {// 获取到图⽚⽂件后let img:any = new Image()img.src = imgObj.target.resultimg.onload = (e:any) => {Compress(img,e.path[0].height,e.path[0].width,(newImg:any) => {this.imgList.push(newImg)this.isLoading = false// 待添加拖拽功能})}}/*** 图⽚压缩* @param img 图⽚对象*/export function Compress(img:any,height:number,width:number,callback:Function) {let canvas:any = document.createElement('canvas')let context:any = canvas.getContext('2d')canvas.width = widthcanvas.height = heightcontext.clearRect(0,0,width,height)context.drawImage(img,0,0,width,height)callback(canvas.toDataURL("image/jpeg", 0.75))}拖拽排序、拖拽删除拖拽排序、拖拽到指定位置删除是通过监听touch事件来实现的。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

xheditor +struts2 文件上传(一般情况和支持HTML5拖拽上传)1、准备工作Struts2.2.3导入相关jar包Xheditor1.1.4引入jquery和xheditor的js文件2、效果图a) 使用上传图片按钮进行上次b) 将图片进行拖入上传(支持html5的浏览器)3、相关代码a)单纯的使用普通方式上传:如下图:Struts2中Action中的方法:和传统的上传没什么区别,记得写getter和setterXheditor官方要求:返回内容必需是标准的json字符串,结构可以是如下:{"err":"","msg":"200906030521128703.gif"} 或者{"err":"","msg":{"url":"200906030521128703.jpg","localfile":"test.jpg","id":"1"}} 注:若选择结构2,则url变量是必有注意:1.上传成功时返回的json字符串是:{"err":"","msg":"200906030521128703.gif"}2.err是””,不能省略,3.方式1,msg返回值是上传成功文件的路径;4.方式2,则msg中的url是上传成功文件的路径5.url第一个字符是!表示立即上传,不需要点确定就插入到textarea中Jsp中:【特别应该注意的是:html5Upload:false;如果不设置成false,在支持html5的浏览器(eg:chrome)中,会默认使用html5上传的方式,导致未设置multipart/form-data上传失败,而在不支持html5,例如IE中正常。

】吐槽一下,xheditor的作者为何不默认上传使用传统方式,且html5Upload默认还是true,官方也没有明显的说明,因为这个问题测试了很久。

b)支持html5的拖拽上传官方说明:HTML5上传的整个POST数据流就是上传的文件完整数据,而本地文件名等信息储存于HTTP_CONTENT_DISPOSITION这个服务器变量中。

也就是说,如果是html5实现的文件上次,我们可以从request的header的Content-Disposition中获得相关数据,可以打开浏览器的网络监测查看。

Struts2中Action中的方法:Jsp中:无任何变化,把html5Upload =true即可注:本程序未对细节做过多的处理,重在实现上传,比如上传文件的限制,上传成功后的回调函数未做处理。

问后附上了完整的程序,本人邮箱623565791@欢迎交流。

4、完整代码下面是完整代码,如果您还有什么问题,可以参考:Struts2packagecom.zhy.xheditor.action;importjava.io.File;importjava.io.IOException;importjava.io.PrintWriter;importjavax.servlet.ServletInputStream;importjavax.servlet.http.HttpServletResponse;mons.io.FileUtils;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;@SuppressWarnings("serial")public class FileUpload extends ActionSupport{public File filedata;public String filedataFileName;public void ajaxFileUpload(){String dirPath = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("");File dir = new File(dirPath + "/resources/upload");String contentDisposition = ServletActionContext.getRequest().getHeader("Content-Disposition");// 如果是HTML5上传文件,那么这里有相应头的if (contentDisposition != null){// HTML5拖拽上传文件Long fileSize = Long.valueOf(ServletActionContext.getRequest().getHeader("Content-Length"));// 上传的文件大小String fileName = contentDisposition.substring(contentDisposition.lastIndexOf("filename=\""));// 文件名称fileName = fileName.replaceAll("filename=\"", "");fileName = fileName.substring(0, fileName.length() - 1);System.out.println(fileName);ServletInputStreaminputStream = null;try{System.out.println("invoked!");inputStream = ServletActionContext.getRequest().getInputStream();if (inputStream != null){FileUtils.copyInputStreamToFile(inputStream, new File(dir,fileName));String msg = "{\"err\":\"\",\"msg\":{\"url\":\"!"+ ServletActionContext.getRequest().getContextPath() + "/resources/upload/"+ fileName+ "\",\"localfile\":\"test.jpg\",\"id\":\"1\"}} ";System.out.println("xheditor using html5 ..." + fileName);writer(msg);System.out.println("xheditor using html5 ..." + fileName);}} catch (IOException e){e.printStackTrace();}return;}try{System.out.println("xheditor using common ..." + filedataFileName);FileUtils.copyFile(filedata, new File(dir, filedataFileName));String msg = "{\"err\":\"\",\"msg\":{\"url\":\"!"+ ServletActionContext.getRequest().getContextPath()+ "/resources/upload/" + filedataFileName+ "\",\"localfile\":\"test.jpg\",\"id\":\"1\"}} ";writer(msg);} catch (IOException e){e.printStackTrace();}}private void writer(String msg){try{System.out.println("invoked!!..");HttpServletResponseresp = ServletActionContext.getResponse();resp.setCharacterEncoding("utf-8");resp.setContentType("text/plain");PrintWriter out = resp.getWriter();out.write(msg);out.flush();} catch (IOException e){e.printStackTrace();}}}Jsp:<%@page language="java"import="java.util.*"pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";%><!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma"content="no-cache"><meta http-equiv="cache-control"content="no-cache"><meta http-equiv="expires"content="0"><meta http-equiv="keywords"content="keyword1,keyword2,keyword3"> <meta http-equiv="description"content="This is my page"><script type="text/javascript"src="<%=request.getContextPath()%>/resources/jquery-1.7.2.js"></script><script type="text/javascript"src="<%=request.getContextPath()%>/resources/xheditor-1.1.14/xhed itor-1.1.14/xheditor-1.1.14-zh-cn.min.js"></script><script type="text/javascript">$(function(){$("#xheditor").xheditor({upLinkUrl:$("#contextPath").val()+"/upload!ajaxFileUpload",upLinkExt:"zip,rar,txt",upImgUrl:$("#contextPath").val()+"/upload!ajaxFileUpload",upImgExt:"jpg,jpeg,gif,png",upFlashUrl:$("#contextPath").val()+"/upload!ajaxFileUpload",upFlashExt:"swf",upMediaUrl:$("#contextPath").val()+"/upload!ajaxFileUpload",upMediaExt:"avi",html5Upload:true,width:800,height:600});});</script></head><body><textarea rows=""cols=""id="xheditor"></textarea> </body><input type="hidden"id="contextPath"value="<%=request.getContextPath()%>"/></html>Struts.xml<?xml version="1.0"encoding="UTF-8"?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "/dtds/struts-2.0.dtd"><struts><constant name="struts.enable.DynamicMethodInvocation"value="true"/> <constant name="struts.devMode"value="false"/><package name="default"namespace="/"extends="struts-default"><action name="upload"class="com.zhy.xheditor.action.FileUpload"> </action></package></struts>。

相关文档
最新文档