[Struts2]struts2 实现文件上传【学习笔记】

文件上传-->upload.jsp :

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
	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 'upload_file.jsp' starting page</title>

</head>

<body>
	<s:form action="/multi-upload-2" method="post"
		enctype="multipart/form-data">
		<s:file name="upload" label="upload1" />
		<s:file name="upload" label="upload2" />
		<s:file name="upload" label="upload3" />
		<s:submit />
	</s:form>
</body>
</html>

MultiUploadFileAction:

    //注意这里的第一个属性名字不是必须这样,但是set方法却必须是下列属性对应的参数
    //(upload前缀取决于form表单中的s:file name="")
    private File[] upload;  (private List<File> upload)
    private String[] uploadContentType;  (private List<String> uploadContentType)
    private String[] uploadFileName;     (private List<String> uploadFileName)


文件上传的步骤:

  1. 创建上传目录:
         String path = ServletActionContext.getServletContext.getRealPath("自定义路径");
         File uploadPath = new File(path);
         if(!uploadPath.exists())
               uploadPath.mkdirs();
          
         FileInputStream in = null;
         FileOutputStream out = null;
  2.生成uuidFileName
         String extendedName = uploadFileName[i].subString(uploadFileName[i].lastIndexOf(".")); 
         String uuidFileName = UUID.randomUUID().toString() + extendedName;
  3.创建文件输入、输出对象
         in = new FileInputStream(upload[i]);
         out = new FileOutputStream(uploadPath + "/" + uuidFileName);
  4.字节流读写数据
         byte[] buf = new byte[1024];
         int len = -1;
         while((len = in.read(buf)) != -1){
              out.write(buf, 0, len);
         }
  5.关闭流对象
         out.close();
         in.close();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值