当前位置:首页 » 文件管理 » javastruts2上传图片

javastruts2上传图片

发布时间: 2023-02-02 06:04:17

1. java Struts2 根据文件路径可以上传附件吗

示例代码:
imForm = () form;
FormFile importFile = imForm.getImportFile();
InputStream is = importFile.getInputStream();

String store_path = request.getSession().getServletContext().getRealPath("/");
String relativePath = "fileupload/smartheat/profitInfo/ServiceProfitInfo_" + nowtime + ".xls";
String filePath = store_path + relativePath;
OutputStream os = new FileOutputStream(filePath);
int bytes = 0;
byte[] buffer = new byte[is.available()];
while((bytes=is.read(buffer, 0, is.available()))!=-1) {
os.write(buffer,0,bytes);
}

2. java的struts2上传文件时为什么这么些、写

String path = ServletActionContext.getServletContext().getRealPath("/images");
这样的写法是为了得到/images的绝对路径
而String path="/images";这就是相对路径了,有时候,可能这种写法程序找不到。

3. 用java完成图片多张批量上传的功能,还有就是后台的应该怎么处理上传的照片。

环境准备

1. 下载并安装Tomcat(已经有很多关于Tomcat安装以及使用的文章,在这里不再介绍);

2. 下载File upload的jar包commons-fileupload-1.0-beta-1.jar,并将该文件拷贝到{$TOMCAT}/common/lib目录下(其中{$TOMCAT}为Tomcat的安装目录);

3. 由于Fileupload子项目同时要用到另外一个项目commons-Beanutils,所以必须下载Beanutils,并将解压后的文件commons-beanutils.jar拷贝到{$TOMCAT}/common/lib目录下。

开发文件上传页面

文件上传的界面如图1所示。为了增加效率我们设计了三个文件域,同时上传三个文件。
图1 文件上传界面

页面的HTML代码如下:

<html>
<head>
<title>文件上传演示</title>
</head>
<body bgcolor=“#FFFFFF”text=“#000000” leftmargin=“0”topmargin=“40”marginwidth=“0” marginheight=“0”>
<center>
<h1>文件上传演示</h1>
<form name=“uploadform”method=“POST” action=“save.jsp”ENCTYPE=“multipart/form-data”>
<table border=“1”width=“450”cellpadding=“4” cellspacing=“2”bordercolor=“#9BD7FF”>
<tr><td width=“100%”colspan=“2”>
文件1:<input name=“file1”size=“40”type=“file”>
</td></tr>
<tr><td width=“100%”colspan=“2”>
文件2:<input name=“file2”size=“40”type=“file”>
</td></tr>
<tr><td width=“100%”colspan=“2”>
文件3:<input name=“file3”size=“40”type=“file”>
</td></tr>
</table>
<br/><br/>
<table>
<tr><td align=“center”><input name=“upload” type=“submit”value=“开始上传”/></td></tr>
</table>
</form>
</center>
</body>
</html>

代码中要特别注意的是黑体处。必须保证表单的ENCTYPE属性值为multipart/form-data,这样浏览器才能正确执行上传文件的操作。

处理上传文件信息

由于本文主要是讲述如何使用Commons-fileupload,所以为了便于修改、调试,上传文件的保存使用一个JSP文件来进行处理。我们将浏览器上传来的所有文件保存在一个指定目录下并在页面上显示所有上传文件的详细信息。保存页面处理结果见图2所示。
图2 保存页面

下面来看看save.jsp的代码:

<%
/**
* 演示文件上传的处理
* @author <a href=“mailto:[email protected]”>Winter Lau</a>
* @version $Id: save.jsp,v 1.00 2003/03/01 10:10:15
*/
%>
<%@ page language=“java”contentType=“text/html;charset=GBK”%>
<%@ page import=“java.util.*”%>
<%@ page import=“org.apache.commons.fileupload.*”%>
<html>
<head>
<title>保存上传文件</title>
</head>
<%
String msg = “”;
FileUpload fu = new FileUpload();
// 设置允许用户上传文件大小,单位:字节
fu.setSizeMax(10000000);
// maximum size that will be stored in memory?
// 设置最多只允许在内存中存储的数据,单位:字节
fu.setSizeThreshold(4096);
// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
fu.setRepositoryPath(“C:\\TEMP”);
//开始读取上传信息
List fileItems = fu.parseRequest(request);
%>
<body bgcolor=“#FFFFFF”text=“#000000” leftmargin=“0”topmargin=“40”marginwidth=“0” marginheight=“0”>
<font size=“6”color=“blue”>文件列表:</font>
<center>
<table cellpadding=0 cellspacing=1 border=1 width=“100%”>
<tr>
<td bgcolor=“#008080”>文件名</td>
<td bgcolor=“#008080”>大小</td>
</tr>
<%
// 依次处理每个上传的文件
Iterator iter = fileItems.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
//忽略其他不是文件域的所有表单信息
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if((name==null||name.equals(“”)) && size==0)
continue;
%>
<tr>
<td><%=item.getName()%></td>
<td><%=item.getSize()%></td>
</tr>
<%
//保存上传的文件到指定的目录
name = name.replace(‘:’,‘_’);
name = name.replace(‘\\’,‘_’);
item.write(“F:\\”+ name);
}
}
%>
</table>

<br/><br/>
<a href=“upload.html”>返回上传页面</a>
</center>
</body>
</html>

在这个文件中需要注意的是FileUpload对象的一些参数值的意义,如下面代码所示的三个参数sizeMax、sizeThreshold、repositoryPath:

FileUpload fu = new FileUpload();
// 设置允许用户上传文件大小,单位:字节
fu.setSizeMax(10000000);
// maximum size that will be stored in memory?
// 设置最多只允许在内存中存储的数据,单位:字节
fu.setSizeThreshold(4096);
// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
fu.setRepositoryPath(“C:\\TEMP”);

这3个参数的意义分别为:

SizeMax 用来设置上传文件大小的最大值,一旦用户上传的文件大小超过该值时将会抛出一个FileUploadException异常,提示文件太大;

SizeThreshold 设置内存中缓冲区的大小,一旦文件的大小超过该值的时候,程序会自动将其它数据存放在repositoryPath指定的目录下作为缓冲。合理设置该参数的值可以保证服务器稳定高效的运行;

RepositoryPath 指定缓冲区目录。

使用注意事项
从实际应用的结果来看该模块能够稳定高效的工作。其中参数SizeThreshold的值至关重要,设置太大会占用过多的内存,设置太小会频繁使用硬盘作为缓冲以致牺牲性能。因此,设置该值时要根据用户上传文件大小分布情况来设定。例如大部分文件大小集中在100KB左右,则可以使用100KB作为该参数的值,当然了再大就不合适了。使用commons-fileupload来处理HTTP文件上传的功能模块很小,但是值得研究的东西很多。

4. struts2上传图片到linux服务器,成功上传文件,无法返回路径,报错: net::ERR_CONTENT_LENGTH_MISMATCH

因为windows和linux系统的文件路径分割符是不一样的。一个是“/”一个是“\”,所以换了环境当热会错。java中有一个方法叫做File.separator可以得到是运行环境下的分隔符,你需要在代码中做出修改。将文件路径拆开后然后使用 File.separator拼接。

5. Struts2下上传图片附件大小验证问题

提交的时候 可以用 AJAX验证 上传文件大小,超出限制直接用JS可以给出提示。
JS没有办法获取文件的大小,因为JS无法操作文件。

6. java struts2 上传时候的代码中action =""引号中的意思是什么

${pageContext.request.contextPath}

得到当前web应用访问名称


后面跟的是一个action的访问方式


这样看,struts.xml中upload_execute这个Action所在的父级package标签中应该有namespace应该是这样:

<package namespace="/control/employee" 其他属性忽略>


不过貌似不用

${pageContext.request.contextPath}也行.你试试

7. javaee 用struts2的文件上传,保存才服务器目录下 服务器是tomcat 为什么电脑重启后 文件就没有了

首先,

文件上传到服务器是保存在磁盘上的,磁盘是永久性存储介质,如果不是手动删除或者中毒(这种可能性不大),是不会丢失的。你可能是上次运行的时候上传的文件在服务器中,后来被你重新发布项目把原项目直接覆盖掉了,因为你原项目中可能没有存你新发布的图片,所以直接丢失掉了,建议如果有重要的上传文件,先将已经上传的文件备份一下,再发布新的项目。或者是你发布新文件的时候设置一下那个发布选项,只覆盖旧文件,不要全部删除后上传新项目,如图

8. java struts1的formbean中我定义了一个FormFile用来接收客户端浏览器上传上来的图片,报下面错,

form表单 添加enctyp=“。。。”,然后给上传域 添加name属性,后天接受name值,然后使用文件流上传。

9. java中怎么利用struts2上传多个pdf文件

通过3种方式模拟多个文件上传
第一种方式
package com.ljq.action;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class UploadAction extends ActionSupport{
private File[] image; //上传的文件
private String[] imageFileName; //文件名称
private String[] imageContentType; //文件类型
public String execute() throws Exception {
ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
String realpath = ServletActionContext.getServletContext().getRealPath("/images");
System.out.println(realpath);
if (image != null) {
File savedir=new File(realpath);
if(!savedir.getParentFile().exists())
savedir.getParentFile().mkdirs();
for(int i=0;i<image.length;i++){
File savefile = new File(savedir, imageFileName[i]);
FileUtils.File(image[i], savefile);
}
ActionContext.getContext().put("message", "文件上传成功");
}
return "success";
}
public File[] getImage() {
return image;
}
public void setImage(File[] image) {
this.image = image;
}
public String[] getImageContentType() {
return imageContentType;
}
public void setImageContentType(String[] imageContentType) {
this.imageContentType = imageContentType;
}
public String[] getImageFileName() {
return imageFileName;
}
public void setImageFileName(String[] imageFileName) {
this.imageFileName = imageFileName;
}
}
第二种方式
package com.ljq.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
* 使用数组上传多个文件
*
* @author ljq
*
*/
@SuppressWarnings("serial")
public class UploadAction2 extends ActionSupport{
private File[] image; //上传的文件
private String[] imageFileName; //文件名称
private String[] imageContentType; //文件类型
private String savePath;
@Override
public String execute() throws Exception {
ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
//取得需要上传的文件数组
File[] files = getImage();
if (files !=null && files.length > 0) {
for (int i = 0; i < files.length; i++) {
//建立上传文件的输出流, getImageFileName()[i]
System.out.println(getSavePath() + "\\" + getImageFileName()[i]);
FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + getImageFileName()[i]);
//建立上传文件的输入流
FileInputStream fis = new FileInputStream(files[i]);
byte[] buffer = new byte[1024];
int len = 0;
while ((len=fis.read(buffer))>0) {
fos.write(buffer, 0, len);
}
fos.close();
fis.close();
}
}
return SUCCESS;
}
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;
}
/**
* 返回上传文件保存的位置
*
* @return
* @throws Exception
*/
public String getSavePath() throws Exception {
return ServletActionContext.getServletContext().getRealPath(savePath);
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
}
第三种方式
package com.ljq.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
* 使用List上传多个文件
*
* @author ljq
*
*/
@SuppressWarnings("serial")
public class UploadAction3 extends ActionSupport {
private List<File> image; // 上传的文件
private List<String> imageFileName; // 文件名称
private List<String> imageContentType; // 文件类型
private String savePath;
@Override
public String execute() throws Exception {
ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
// 取得需要上传的文件数组
List<File> files = getImage();
if (files != null && files.size() > 0) {
for (int i = 0; i < files.size(); i++) {
FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + getImageFileName().get(i));
FileInputStream fis = new FileInputStream(files.get(i));
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fis.close();
fos.close();
}
}
return SUCCESS;
}
public List<File> getImage() {
return image;
}
public void setImage(List<File> image) {
this.image = image;
}
public List<String> getImageFileName() {
return imageFileName;
}
public void setImageFileName(List<String> imageFileName) {
this.imageFileName = imageFileName;
}
public List<String> getImageContentType() {
return imageContentType;
}
public void setImageContentType(List<String> imageContentType) {
this.imageContentType = imageContentType;
}
/**
* 返回上传文件保存的位置
*
* @return
* @throws Exception
*/
public String getSavePath() throws Exception {
return ServletActionContext.getServletContext().getRealPath(savePath);
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
}
struts.xml配置文件
<?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>
<!-- 该属性指定需要Struts2处理的请求后缀,该属性的默认值是action,即所有匹配*.action的请求都由Struts2处理。
如果用户需要指定多个请求后缀,则多个后缀之间以英文逗号(,)隔开。 -->
<constant name="struts.action.extension" value="do" />
<!-- 设置浏览器是否缓存静态内容,默认值为true(生产环境下使用),开发阶段最好关闭 -->
<constant name="struts.serve.static.browserCache" value="false" />
<!-- 当struts的配置文件修改后,系统是否自动重新加载该文件,默认值为false(生产环境下使用),开发阶段最好打开 -->
<constant name="struts.configuration.xml.reload" value="true" />
<!-- 开发模式下使用,这样可以打印出更详细的错误信息 -->
<constant name="struts.devMode" value="true" />
<!-- 默认的视图主题 -->
<constant name="struts.ui.theme" value="simple" />
<!--<constant name="struts.objectFactory" value="spring" />-->
<!--解决乱码 -->
<constant name="struts.i18n.encoding" value="UTF-8" />
<constant name="struts.multipart.maxSize" value="10701096"/>
<package name="upload" namespace="/upload" extends="struts-default">
<action name="*_upload" class="com.ljq.action.UploadAction" method="{1}">
<result name="success">/WEB-INF/page/message.jsp</result>
</action>
</package>
<package name="upload1" namespace="/upload1" extends="struts-default">
<action name="upload1" class="com.ljq.action.UploadAction2" method="execute">
<!-- 要创建/image文件夹,否则会报找不到文件 -->
<param name="savePath">/image</param>
<result name="success">/WEB-INF/page/message.jsp</result>
</action>
</package>
<package name="upload2" namespace="/upload2" extends="struts-default">
<action name="upload2" class="com.ljq.action.UploadAction3" method="execute">
<!-- 要创建/image文件夹,否则会报找不到文件 -->
<param name="savePath">/image</param>
<result name="success">/WEB-INF/page/message.jsp</result>
</action>
</package>
</struts>
上传表单页面upload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>文件上传</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
<!-- ${pageContext.request.contextPath}/upload/execute_upload.do -->
<!-- ${pageContext.request.contextPath}/upload1/upload1.do -->
<!-- ${pageContext.request.contextPath}/upload2/upload2.do -->
<!-- -->
<form action="${pageContext.request.contextPath}/upload2/upload2.do" enctype="multipart/form-data" method="post">
文件1:<input type="file" name="image"><br/>
文件2:<input type="file" name="image"><br/>
文件3:<input type="file" name="image"><br/>
<input type="submit" value="上传" />
</form>
</body>
</html>
显示页面message.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'message.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">
</head>
<body>
上传成功
<br/>
<s:debug></s:debug>
</body>
</html>

10. java 中如何向服务器上传图片

我们使用一些已有的组件帮助我们实现这种上传功能。
常用的上传组件:
Apache 的 Commons FileUpload
JavaZoom的UploadBean
jspSmartUpload
以下,以FileUpload为例讲解
1、在jsp端
<form id="form1" name="form1" method="post" action="servlet/fileServlet" enctype="multipart/form-data">
要注意enctype="multipart/form-data"
然后只需要放置一个file控件,并执行submit操作即可
<input name="file" type="file" size="20" >
<input type="submit" name="submit" value="提交" >
2、web端
核心代码如下:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8"));
} else {
if (item.getName() != null && !item.getName().equals("")) {
System.out.println("上传文件的大小:" + item.getSize());
System.out.println("上传文件的类型:" + item.getContentType());
System.out.println("上传文件的名称:" + item.getName());
File tempFile = new File(item.getName());
File file = new File(sc.getRealPath("/") + savePath, tempFile.getName());
item.write(file);
request.setAttribute("upload.message", "上传文件成功!");
}else{
request.setAttribute("upload.message", "没有选择上传文件!");
}
}
}
}catch(FileUploadException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("upload.message", "上传文件失败!");
}
request.getRequestDispatcher("/uploadResult.jsp").forward(request, response);
}

热点内容
编译原理什么内容 发布:2024-04-28 00:01:33 浏览:477
安卓手机怎么登录ipadid 发布:2024-04-27 23:52:25 浏览:670
浏览量和访问次数 发布:2024-04-27 23:44:56 浏览:475
在linuxpython 发布:2024-04-27 22:38:57 浏览:316
机顶盒密码是在哪里 发布:2024-04-27 22:32:47 浏览:158
名图买哪个配置值得买 发布:2024-04-27 22:32:36 浏览:878
比亚迪秦pro选哪个配置好 发布:2024-04-27 22:32:34 浏览:534
logn算法 发布:2024-04-27 21:58:36 浏览:596
11选五的简单算法 发布:2024-04-27 21:46:14 浏览:71
ebay图片上传 发布:2024-04-27 21:31:50 浏览:587