- 浏览: 4918728 次
- 性别:
- 来自: 上海
文章分类
- 全部博客 (743)
- JAVA (44)
- JAVA 乔乐共享 (145)
- js (132)
- database (26)
- jQuery (46)
- velocity (16)
- Ubuntu (14)
- Grails (2)
- Groovy (6)
- xml (2)
- Spring (11)
- mysql (24)
- sqlserver (6)
- oracle (9)
- cmd (8)
- CSS (17)
- Linux (2)
- sqlite (4)
- php (11)
- json (2)
- laravel (2)
- html (3)
- 闲聊 (3)
- git (13)
- nodejs (25)
- angularjs (17)
- npm (8)
- bootstrap (4)
- mongodb (5)
- React (32)
- Crack (7)
- b (0)
- ES6 (2)
- webpack (3)
- Babel (1)
- Koa (1)
最新评论
-
taoshengyijiuzt:
感谢大佬!!!
JetBrains最新激活服务器(长期更新ing) -
masuweng:
激活码可以用
JetBrains最新激活服务器(长期更新ing) -
dusdong:
都失效了
JetBrains最新激活服务器(长期更新ing) -
追风筝的孩纸Zz:
dddddddddddddddd
js获取网页屏幕可见区域高度 -
自己811005:
88350bcf69dcfbda7f8a76a589d9054 ...
Js设置前端允许跨域请求后端API:Access-Control-Allow-Credentials
Create view files:
Let us start with creating our view which will be required to browse and upload a selected file. So let us create a index.jsp with plain HTML upload form that allows the user to upload a file:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
<label for="myFile">Upload your file</label>
<input type="file" name="myFile" />
<input type="submit" value="Upload"/>
</form>
</body>
</html>
There are couple of points worth noting in the above example. First of all, the form's enctype is set to multipart/form-data. This should be set so that file uploads are handled successfully by the file upload interceptor. The next point noting is the form's action method upload and the name of the file upload field - which is myFile. We need this information to create the action method and the struts configuration.
Next let us create a simple jsp file success.jsp to display the outcome of our file upload in case it becomes success.
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>File Upload Success</title>
</head>
<body>
You have successfully uploaded <s:property value="myFileFileName"/>
</body>
</html>
Following will be the result file error.jsp in case there is some error in uploading the file:
Create action class:
Next let us create a Java class called uploadFile.java which will take care of uploading file and storing that file at a secure location:
The uploadFile.java is a very simple class. The important thing to note is that the FileUpload interceptor along with the Parameters Intercetpor does all the heavy lifting for us. The FileUpload interceptor makes three parameters available for you by default. They are named in the following pattern:
[your file name parameter] - This is the actual file that the user has uploaded. In this example it will be "myFile"
[your file name parameter]ContentType - This is the content type of the file that was uploaded. In this example it will be "myFileContentType"
[your file name parameter]FileName - This is the name of the file that was uploaded. In this example it will be "myFileFileName"
The three parameters are available for us, thanks to the Struts Interceptors. All we have to do is to create three parameters with the correct names in our Action class and automaically these variables are auto wired for us. So, in the above example, we have three parameters and an action method that simply returns "success" if everything goes fine otherwise it returns "error".
Configuration files:
Following are the Struts2 configuration properties that control file uploading process:
Let us start with creating our view which will be required to browse and upload a selected file. So let us create a index.jsp with plain HTML upload form that allows the user to upload a file:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
<label for="myFile">Upload your file</label>
<input type="file" name="myFile" />
<input type="submit" value="Upload"/>
</form>
</body>
</html>
There are couple of points worth noting in the above example. First of all, the form's enctype is set to multipart/form-data. This should be set so that file uploads are handled successfully by the file upload interceptor. The next point noting is the form's action method upload and the name of the file upload field - which is myFile. We need this information to create the action method and the struts configuration.
Next let us create a simple jsp file success.jsp to display the outcome of our file upload in case it becomes success.
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>File Upload Success</title>
</head>
<body>
You have successfully uploaded <s:property value="myFileFileName"/>
</body>
</html>
Following will be the result file error.jsp in case there is some error in uploading the file:
<%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>File Upload Error</title> </head> <body> There has been an error in uploading the file. </body> </html>
Create action class:
Next let us create a Java class called uploadFile.java which will take care of uploading file and storing that file at a secure location:
package com.tutorialspoint.struts2; import java.io.File; import org.apache.commons.io.FileUtils; import java.io.IOException; import com.opensymphony.xwork2.ActionSupport; public class uploadFile extends ActionSupport{ private File myFile; private String myFileContentType; private String myFileFileName; private String destPath; public String execute() { /* Copy file to a safe location */ destPath = "C:/apache-tomcat-6.0.33/work/"; try{ System.out.println("Src File name: " + myFile); System.out.println("Dst File name: " + myFileFileName); File destFile = new File(destPath, myFileFileName); FileUtils.copyFile(myFile, destFile); }catch(IOException e){ e.printStackTrace(); return ERROR; } return SUCCESS; } public File getMyFile() { return myFile; } public void setMyFile(File myFile) { this.myFile = myFile; } public String getMyFileContentType() { return myFileContentType; } public void setMyFileContentType(String myFileContentType) { this.myFileContentType = myFileContentType; } public String getMyFileFileName() { return myFileFileName; } public void setMyFileFileName(String myFileFileName) { this.myFileFileName = myFileFileName; } }
The uploadFile.java is a very simple class. The important thing to note is that the FileUpload interceptor along with the Parameters Intercetpor does all the heavy lifting for us. The FileUpload interceptor makes three parameters available for you by default. They are named in the following pattern:
[your file name parameter] - This is the actual file that the user has uploaded. In this example it will be "myFile"
[your file name parameter]ContentType - This is the content type of the file that was uploaded. In this example it will be "myFileContentType"
[your file name parameter]FileName - This is the name of the file that was uploaded. In this example it will be "myFileFileName"
The three parameters are available for us, thanks to the Struts Interceptors. All we have to do is to create three parameters with the correct names in our Action class and automaically these variables are auto wired for us. So, in the above example, we have three parameters and an action method that simply returns "success" if everything goes fine otherwise it returns "error".
Configuration files:
Following are the Struts2 configuration properties that control file uploading process:
SN Properties & Description 1 struts.multipart.maxSize The maximum size (in bytes) of a file to be accepted as a file upload. Default is 250M. 2 struts.multipart.parser The library used to upload the multipart form. By default is jakarta 3 struts.multipart.saveDir The location to store the temporary file. By default is javax.servlet.context.tempdir. In order to change any of theses settings you can use constant tag in your applications struts.xml file, as I did to change the maximum size of a file to be uploaded. Let us have our struts.xml as follows:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <constant name="struts.multipart.maxSize" value="1000000" /> <package name="helloworld" extends="struts-default"> <action name="upload" class="com.tutorialspoint.struts2.uploadFile"> <result name="success">/success.jsp</result> <result name="error">/error.jsp</result> </action> </package> </struts>Because FileUpload interceptor is a part of the defaultStack of interceptors, we do not need to configure it explicity. But you can add <interceptor-ref> tag inside <action>. The fileUpload interceptor takes two parameters (a) maximumSize and (b) allowedTypes. The maximumSize parameter sets the maximum file size allowed (the default is approximately 2MB).The allowedTypes parameter is a comma-separated list of accepted content (MIME) types as shown below:<action name="upload" class="com.tutorialspoint.struts2.uploadFile"> <interceptor-ref name="basicStack"> <interceptor-ref name="fileUpload"> <param name="allowedTypes">image/jpeg,image/gif</param> </interceptor-ref> <result name="success">/success.jsp</result> <result name="error">/error.jsp</result> </action>
Following is the content of web.xml file:<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Struts 2</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
Now Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/upload.jsp. This will give you following screen:
Now select a file "Contacts.txt" using Browse button and click upload button which will upload the file on your serve and you should see the net page. You can check the uploaded file should be saved in C:\apache-tomcat-6.0.33\work.
Note that the FileUpload Interceptor deletes the uploaded file automatically so you would have to save uploaded file programatically at some location before it gets deleted.
Error Messages:
The fileUplaod interceptor uses several default error message keys:SN Error Message Key & Description 1 struts.messages.error.uploading A general error that occurs when the file could not be uploaded. 2 struts.messages.error.file.too.large Occurs when the uploaded file is too large as specified by maximumSize. 3 struts.messages.error.content.type.not.allowed Occurs when the uploaded file does not match the expected content types specified. You can override the text of these messages in WebContent/WEB-INF/classes/messages.properties resource files.发表评论
-
Ubuntu VirtualBox 安装win10报错:FATAL: No bootable medium found! System halted.
2017-04-20 13:04 6240点击设置:->Storage存储-&g ... -
win10 webstorm9和10无法使用terminal解决方案
2015-06-07 16:41 15931原因:计算机从win7更新到win10,webstorm9 ... -
String,StringBuffer与StringBuilder的区别
2014-07-21 13:22 1090String StringBuffer Strin ... -
HashMap与HashTable的区别(含源码分析)
2014-07-21 12:58 1263HashMap HashTable Hash ... -
java判断中英文长度并截取部分添加省略号
2014-03-21 15:44 2545public static void main(Strin ... -
JAVA比较两个日期的差值天数
2014-01-17 11:44 6108package com.anxin.ssk.cache; ... -
Eclipse GBK代码转移到UFT-8编码上去,迁移方案
2013-03-18 14:40 5439方法一:(程序法)推荐 //用commons-io.jar ... -
CMD命令一键备份文件目录
2013-01-30 15:43 2318echo 开始备份SSK目录 ::设置临时变量为目标备 ... -
Navicat 中文乱码问题
2012-09-25 16:47 3888解决方法: 1、关闭数据库连接; 2、右击数据库选择“连接 ... -
java写入xml格式数据增强版-可递归进行多层嵌套
2012-08-20 13:30 4611package com.proxy.util; im ... -
Java XMLWriter 快速创建xml文件
2012-08-17 16:23 2294package com.proxy.util; im ... -
Java循环复杂map,foreach
2012-08-17 16:11 9917package com.proxy.util; im ... -
Java超全Json工具类JsonUtil
2012-08-15 17:17 23059import java.io.StringReader; ... -
java占位符像C#{0}那样简单
2012-08-14 16:20 3752import java.text.MessageForma ... -
jQuery判断对象是否显示或隐藏
2012-08-08 17:05 19245// jQuery("#tanchuBg&quo ... -
通过dos命令获得服务器网卡地址-适合Windows和Linux
2012-08-01 17:07 1484/** * 获得服务器网卡地址 * * @ ... -
js正则表达式过去\反斜杠的问题解决方案
2012-06-01 15:22 3081text_keyword_tags = text_keyw ... -
struts+json所含的jar包全集
2012-05-30 14:03 1378Directory of E:\Happy\Deskto ... -
Java新建线程异步调用示例
2012-05-17 11:07 1954new Thread(new Runnable() { ... -
Java替换字符串正则表达式和其3种方法
2012-05-17 11:05 3328public static void main(Strin ...
相关推荐
确保`struts2-core`和`struts2-convention-plugin`以及`struts2-file-uploading-plugin`在你的类路径中。 2. 配置struts.xml:在`struts.xml`配置文件中,启用文件上传,设置`struts.multipart.saveDir`属性指定...
Struts2作为一款流行的Java Web框架,提供了丰富的功能来处理用户表单数据,其中包括文件上传。文件上传在现代Web应用中十分常见,如用户头像、文档分享等场景。Struts2提供了两种主要的文件上传方式:单文件上传和...
File destinationFile = new File("uploads/" + fileFileName); Files.copy(file, destinationFile, StandardCopyOption.REPLACE_EXISTING); return "success"; } catch (IOException e) { addFieldError("file...
通常,你需要引入`struts2-convention-plugin`和`struts2-file-uploading-plugin`。 2. **表单设置**: 在HTML或JSP页面中,创建一个包含`enctype="multipart/form-data"`属性的表单,这指示浏览器以多部分格式...
Struts2是一个基于MVC(Model-View-Controller)设计模式的Java web框架,它极大地简化了Java web应用的开发工作。在Struts2中,文件上传是一个常见的需求,尤其在用户需要提交表单并附带文件时。下面将详细阐述如何...
此外,使用 `<s:file>` 标签将文件上传控件与 Action 中的某个字段(如 `myFile`)绑定,这样 Struts 2 就知道如何处理文件上传请求。 下面是一个简单的 `FileUpload.jsp` 示例: ```jsp ; charset=utf-8" ...
File saveDir = new File("uploads"); if (!saveDir.exists()) { saveDir.mkdir(); } File savedFile = new File(saveDir, imageFileName); FileUtils.copyInputStreamToFile(imageFile.getInputStream(), ...
然后,在Struts2的Action类中,可以创建一个`File`或`java.io.File`类型的属性,用于接收上传的文件。同时,还需要一个对应的`String`类型属性来保存文件名。例如: ```java private File file; private String ...
File saveFile = new File("uploads/" + uploadFileFileName); file.write(saveFile); // 处理其他逻辑... } catch (Exception e) { // 处理异常... } return "success"; } ``` 5. **安全考虑**:文件上传时...
Struts2是一个强大的MVC(模型-视图-控制器)框架,广泛应用于Java Web开发中。在实际项目中,文件上传和下载功能是必不可少的,本实例将详细讲解如何在Struts2框架下实现单个文件及多个文件的上传与下载。 首先,...
Struts2是一个流行的Java web框架,它为开发者提供了一种结构化的MVC(Model-View-Controller)设计模式实现方式,使得开发企业级应用程序变得更加高效和便捷。在Struts2中,实现多文件上传功能是常见的需求,尤其在...
当用户提交表单时,Struts2框架会将文件内容传递到Action类的`File`属性。在Action的execute方法中,可以使用Apache Commons FileUpload库来处理上传的文件。首先,确保在项目中引入了该库。然后,可以解析请求并...
你需要使用Struts2提供的`File`和`FileName`注解来处理上传的文件。例如: ```java public class UploadAction extends ActionSupport { private File file; private String fileName; @FileUpload public ...
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File("uploads/" + file.getOriginalFilename()))); stream.write(bytes); stream.close(); // 提示保存成功 } catch ...
在Struts2中,我们可以使用`struts2-convention-plugin`或者`struts2-core`提供的`<s:file>`标签来创建一个用于上传文件的表单元素。例如: ```html <s:file name="image" label="选择图片"/> 上传"/> ``` ...
File saveDir = new File("uploads"); if (!saveDir.exists()) { saveDir.mkdirs(); } FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(new File(saveDir, ...
File targetFile = new File("uploads/" + fileFileName); FileUtils.copyFile(file, targetFile); // 可以在此处进行其他业务逻辑处理,如数据库存储等 // ... return SUCCESS; } catch (Exception e) { ...
<constant name="struts.multipart.saveDir" value="/tmp/struts2-uploads/"/> <param name="maximumSize">4100000 <param name="allowedTypes">image/jpeg,image/gif,application/pdf ...
Struts2是一个非常流行的Java Web框架,用于构建可维护、可扩展且易于开发的企业级应用程序。在Struts2中,实现文件上传功能是一项常见的需求,它允许用户通过Web界面上传文件到服务器。以下是对该主题的详细解释: ...
Struts2是一个强大的Java web框架,它为开发者提供了一种优雅的方式来实现MVC(Model-View-Controller)架构。在Struts2中,文件上传功能是相当常见的需求,尤其是在处理用户提交表单时,比如上传图片、文档等。本文...