当前位置:首页 » 文件管理 » struts上传附件

struts上传附件

发布时间: 2023-07-21 04:55:30

❶ struts 文件上传错误

Struts2本身提供了一个文件上传的拦截器,通过配置该拦截器可以更轻松地实现文件过滤。我们只需要在Action中配置该拦截器就可以了。当文件过滤失败后,会自动转向input逻辑视图,因此必须为该Action配置名为input的逻辑视图,除此之外还必须为配置defaultStack的拦截器的引用。配置文件如下:

<action name="upload" class="com.annlee.upload.UploadAction" >
<!-- 配置fileUpload的拦截器 -->
<interceptor-ref name="fileUpload">
<!-- 配置允许上传的文件类型 -->
<param name="allowedTypes">image/bmp,image/gif,image/jpg</param>
<!-- 配置允许上传的文件大小 -->
<param name="maximumSize">2000000</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>

<param name="savePath">/</param>
<result>/common/succ.jsp</result>
<result name="input">/cos_fileupload/fileupload.jsp</result>
</action>

如果上传失败系统会返回到原来的页面,要在原来的页面上加上以下错误提示代码:

<s:fielderror />这样系统就会返回提示给用户,但是这时的提示是Struts2自带的提示,非常不友好,我们可以国际化资源里配置以下两项,我们的提示就会自动替换Struts2的提示,提示的关键字如下

struts.messages.error.file.too.large

struts.messages.error.content.type.not.allowed

此外,如果用户上传失败的原因不是因为以上两种还有另外的一个信息提示用户,它的关健字是:struts.messages.error.uploading,我们也应该替换这个提示信息。

其它说明:如果没有指定临时的保存文件夹,系统就会使用javax.servlet.context.tempdir路径,这个路径是Tomcat的work\Catalina\localhost\,我们应该设置自己的路径,这个配置的属性为struts.multipart.saveDir可以在struts.properties中配置,还有一个文件上传的属性:struts.multipart.maxSize设置整个表单请求内容的最大字节数。

❷ struts2实现图片的上传和下载

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.*;
import com.zdvictory.taurus.common.util.*;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;

/** *
*/
public class UploadFileHandler {

private static int BUFFER_SIZE = 8192;

/**
* 上传附件操作 传递参数:系统参数配置设置的参数名称
*/
@SuppressWarnings("unchecked")
public static List<Attachment> upload(String sysParaName) throws Exception {
// 文件保存路径
String path = SysParaFinder.getSysParaValue(sysParaName);
List<Attachment> list = new ArrayList<Attachment>();
MultiPartRequestWrapper request = (MultiPartRequestWrapper) ServletActionContext
.getRequest();
Enumeration enu = request.getFileParameterNames();
while (enu.hasMoreElements()) { // 对每一个文件域进行遍历
String controlName = (String) enu.nextElement();
String[] fileNames = request.getFileNames(controlName);
File[] uploadFiles = request.getFiles(controlName);
for (int i = 0; i < uploadFiles.length; i++) {
File uploadFile = uploadFiles[i];
if (!uploadFile.exists())
continue;
// 如果文件夹不存在,创建文件夹,将文件保存到目录
File dir = new File(request.getRealPath("/") + path);
if (!dir.exists())
dir.mkdirs();
String ext = fileNames[i].substring(fileNames[i].indexOf("."),
fileNames[i].length());// 获取文件扩展名
String filename = UUID.randomUUID().toString() + ext;
File file = new File(request.getRealPath("/") + path + filename);
byte[] data = new byte[BUFFER_SIZE];
int byteRead = -1;
FileInputStream in = new FileInputStream(uploadFile);
FileOutputStream out = new FileOutputStream(file);
while ((byteRead = in.read(data)) != -1) {
out.write(data, 0, byteRead);
out.flush();
}
out.close();
in.close();
// 设置附件对象属性
Attachment attach = new Attachment();
attach.setFilename(fileNames[i]);
attach.setContentType(ext);
attach.setFilepathname(path + filename);
attach.setFilesize(uploadFile.length());
list.add(attach);
}
}
return list;
}
}
文件下载

public String download() throws Exception {
redheadTemplate = redheadTemplateManager.findById(Long
.valueOf(getId()[0]));
String name = redheadTemplate.getName()
+ redheadTemplate.getFilepathname().substring(
redheadTemplate.getFilepathname().lastIndexOf("."),
redheadTemplate.getFilepathname().length());
this.setFilename(new String(name.getBytes(), "ISO8859-1"));
this.setFilepathname(redheadTemplate.getFilepathname());
return "download";
}
文件下载配置文件

<result name="download" type="stream">
<!-- 下载文件类型 -->
<param name="contentType">
application/octet-stream
</param>
<!-- 默认为 inline(在线打开),设置为 attachment 将会告诉浏览器下载该文件,filename 指定下载文
件保存时的文件名,若未指定将会是以浏览的页面名作为文件名,如以 download.action 作为文件名,
这里使用的是动态文件名,${filename}, 它将通过 Action 的 getFilename() 获得文件名 -->
<param name="contentDisposition">
attachment;filename="${filename}"
</param>
<!-- 下载的InputStream流,Struts2自动对应Action中的getDownloadFile方法,该方法必须返回InputStream类型 -->
<param name="inputName">downloadFile</param>
<!-- 输出时缓冲区的大小 -->
<param name="bufferSize">8192</param>
</result>

❸ struts2如何同时上传文件以及获得表单数据

事实上这根本不需要什么其他配置操作,因为这是Struts2,而不是原生Servlet,在Struts2中,拦截器会将request中的表单数据(或者文件格式的数据)都和action类中的属性名称一一对应的注入值(包括文件数据)。所以你需要做的,其实只是在jsp页面(或html)中加入一个file类型的input标签,名称记住(比如为photo),然后在action类中加一个File类型(java.io.File)字段,此字段必须和刚刚的input标签name属性一致,即photo(private File photo;)。最后,需要注意的是,当你妄图从网页上传一个文件类型的表单时,必须将包围它的form类将enctype="multipart/form-data" method="post"加上,即method必须为post,且enctype,也就是表单数据类型,必须为二进制的。

❹ 我用struts2做的上传文件功能,但当文件超过2G时页面出现错误,这个有什么办法解决么

struts配置文件里有个上传大小的常量可以配
可以配置default.properties文件,也可以直接配xml常量
常量名是struts.multipart.maxSize
值的话你自己换算就好了 1K*1024*1024什么什么的自己乘完放到value里

❺ 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);
}

❻ java附件上传功能,上传的附件要根据时间来重命名,上传的路径保存在服务器指定目录根据年月来分的目录里

如果使用框架的话,比如 struts ,就比较简单了
获取上传的时间:
Calendar cal = Calendar.getInstance();
String year = String.valueOf(cal.get(Calendar.YEAR));
String month = String.valueOf(cal.get(Calendar.MONTH));
获取路径:
String path = ServletActionContext.getServletContext().getRealPath("/"+year+"/"+month);
直接保存在 path 这个目录里面就可以

如果没有使用 框架,可以使用 FileUpload 这个 jar 包来上传文件

❼ ssh 多文件上传,怎么实现

多附件struts 1.x,以下代码由agatezone提供。
1.Jsp要用javascript
2.form必须enctype="multipart/form-data"
3.action要用form.getMultipartRequestHandler()获取文件并存储
struts2 更简单,google之。

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>struts1.x upload example</title>
<script type="text/javascript">
function addFileField() {
input_filesCount = document.getElementById("filesCount");
input_filesCount.setAttribute("value", parseInt(input_filesCount.getAttribute("value")) + 1)
div_files = document.getElementById("files");
br = document.createElement("br");
file = document.createElement("input");
text = document.createTextNode("File " + input_filesCount.getAttribute("value") + " : ");
file.setAttribute("type", "file");
file.setAttribute("name", "file" + input_filesCount.getAttribute("value"));
div_files.appendChild(text);
div_files.appendChild(file);
div_files.appendChild(br);
}
</script>
</head>
<body>
<form action="upload.do" method="post" enctype="multipart/form-data">
<input id="filesCount" type="hidden" name="filesCount" value="1" />
<div id="files">
File 1 :
<input type="file" name="file1" />
<br />
</div>
<input type="button" onclick="javascript:addFileField();"
value="add a file" />
<br />
<input type="submit" />
</form>
</body>
</html>

---------------------------------------
package cn.agatezone.example.struts1x.upload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

public class UploadAction extends Action {
@SuppressWarnings("unchecked")
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {

String dirPath = getServlet().getServletContext().getRealPath("/") + "upload";
Hashtable fileh = form.getMultipartRequestHandler().getFileElements();
for (Enumeration e = fileh.keys(); e.hasMoreElements();) {
String key = (String) e.nextElement();
try {
FormFile formfile = (FormFile) fileh.get(key);
String filename = formfile.getFileName().trim(); // 文件名
/*
* @注意!!!
* 这里我没有处理中文,但是如果想要中文无问题,
* 可以设置tomcat的server.xml中的URIEncoding="UTF-8"
*
* 但是,要是不设置的话可以自己用代码解决问题!
* 为了简单明了,本例只作为struts1.x上传部分展示。
*/
if (!"".equals(filename)) {
// 不同的浏览器传上的文件名可能有区别,有的是全路径的
// 在这里保存文件
InputStream ins = formfile.getInputStream();
OutputStream os = new FileOutputStream(dirPath + File.separatorChar + filename);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();

}
} catch (Exception ex) {
System.out.println("出错了!\n" + ex);
}
}

return mapping.findForward("success");

}

}

---------------------------------------------------------
锐志陈鹏 专注Java/.Net培训
锐志技术社区:http://www.witshare.org/bbs/

❽ java 上传附件实现方法

上传附件,实际上就是将文件存储到远程服务器,进行临时存储。举例:
**
* 上传文件
*
* @param fileName
* @param plainFilePath 文件路径路径
* @param filepath
* @return
* @throws Exception
*/
public static String fileUploadByftp(String plainFilePath, String fileName, String filepath) throws Exception {
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
FTPClient ftpClient = new FTPClient();
String bl = "false";
try {
fis = new FileInputStream(plainFilePath);
bos = new ByteArrayOutputStream(fis.available());
byte[] buffer = new byte[1024];
int count = 0;
while ((count = fis.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
bos.flush();
Log.info("加密上传文件开始");
Log.info("连接远程上传服务器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22);
ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);
ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);
FTPFile[] fs;
fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(filepath)) {
bl="true";
ftpClient.changeWorkingDirectory("/"+filepath+"");
}
}
Log.info("检查文件路径是否存在:/"+filepath);
if("false".equals(bl)){
ViewUtil.dataSEErrorPerformedCommon( "查询文件路径不存在:"+"/"+filepath);
return bl;
}
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("GBK");
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.storeFile(fileName, fis);
Log.info("上传文件成功:"+fileName+"。文件保存路径:"+"/"+filepath+"/");
return bl;
} catch (Exception e) {
throw e;
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
if (bos != null) {
try {
bos.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
}
}
备注:只需要修改上传的服务器地址、用户名、密码即可进行服务器访问上传。根据实际需要修改即可。

热点内容
手机wps密码怎么取消密码 发布:2025-02-04 00:51:44 浏览:593
算法逻辑表 发布:2025-02-04 00:51:44 浏览:238
零售股票如何配置主线 发布:2025-02-04 00:51:07 浏览:945
预算法施行时间是 发布:2025-02-04 00:50:30 浏览:339
世界ol上传照片 发布:2025-02-04 00:34:13 浏览:60
有初始化的数组编译提示重复定义 发布:2025-02-04 00:33:21 浏览:583
家里电脑wifi密码怎么改 发布:2025-02-04 00:27:35 浏览:409
手机网页缓存视频 发布:2025-02-03 23:38:48 浏览:835
agnes算法 发布:2025-02-03 23:38:05 浏览:38
私密上传在哪 发布:2025-02-03 23:33:04 浏览:1005