欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Struts2上传下载(使用Oracle数据库存储)

程序员文章站 2022-07-12 16:48:23
...

Struts2上传下载(使用Oracle数据库存储)

1.文件上传的实现(多个附件)

本例以上传多个附件为例,实现Struts2保存Oracle Blob字段的上传功能

需要前台传到后台的参数如下:

(1).用户上传的所有附件列表:private List<File> attachments;

(2).用户上传的所有附件名,用逗号分隔,例如:附件1,附件2,附件3

private String attachmentFileName;

(3).getter/setter方法省略

(4).上传附件的具体实现

Action代码:

if(attachmentFileName!=null){
                               //分割附件名
				String name[] = attachmentFileName.split(", ");
				int i = 0;
				for(File f : attachment){
                                        //循环获得输入流
					InputStream in = new FileInputStream(f);
                                       //调用Service上传的方法
					this.checkWorkService.uploadAttach(in, name[i++].trim());
					in.close();
				}
			}

 Service代码:

	public CheckWorkRecordAttach uploadAttach(InputStream inputStream,
String attachmentName) throws Exception {
                //输出流
		ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
		int ch;
		byte[] buffer = new byte[1024];
                //编码转换,后经测试发现无用
		// String str = new String(buffer,"utf-8");
		// String str2 = new String(str.getBytes("iso-8859-1"),"utf-8");
		// byte buffers[] = str2.getBytes();
		while ((ch = inputStream.read(buffer)) > 0) {
			bytestream.write(buffer, 0, ch);
		}
		// 将输入流写成BYTE数组
		byte[] data = bytestream.toByteArray();
		bytestream.close();
		// 将BYTE数组变成BLOB对象
		Blob attachmentCont = Hibernate.createBlob(data);
                //保存到数据库
		CheckWorkRecordAttach attach = new CheckWorkRecordAttach();
		attach.setAttachmentName(attachmentName);
		attach.setAttachmentUuid(uuid);
		attach.setUploadTime(new Date());
		attach.setState(0);
		attach.setAttachmentCont(attachmentCont);
		attach = this.getCheckWorkRecordAttachDao().save(attach);
		return attach;
	}

 文件上传完成!!

2.文件下载的实现(修复附件中文名乱码)

需要前台传到后台的参数如下:

(1).附件名:private String attachmentFileName;

(2).附件ID:private String attachId;

(3).getter/setter方法省略

/*附件下载*/
/*前台代码*/
function download(id,fileName){
	window.location.href = "../downloadAttach/assignWork_downLoad?attachmentFileName="+fileName+"&&attachId="+id;
}

 

(4).下载附件的后台代码实现

//附件名的getter,setter方法,防止中文名乱码
	public String getAttachmentFileName() {
		return this.attachmentFileName;
	}

	public void setAttachmentFileName(String attachmentFileName) {
		try {
			this.attachmentFileName = new String(attachmentFileName.getBytes("ISO-8859-1"), "utf-8");
		} catch (UnsupportedEncodingException e) {
			logger.error("附件名转换失败", e);
			this.attachmentFileName = "未知";
		};
	}

 Action代码(需要返回InputStream):

	/**
	 * 附件下载
	 * @return
	 */
	public String downLoad(){
		try {
			//防止中文附件名乱码
			 ServletActionContext.getResponse().setHeader("Content-Disposition", "attachment;fileName="
                     + java.net.URLEncoder.encode(this.attachmentFileName,"UTF-8"));
			inputStream = this.assignWorkService.downLoad(Integer.parseInt(attachId));
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

 Service代码(返回InputStream):

	/**
	 * 附件下载
	 */
	@Transactional
	public InputStream downLoad(int attachId) throws Exception {
		//根据ID获取附件
		PersonalWorkReportAttach personalWorkReportAttach = this.personalWorkReportAttachDao.get(attachId);
		//附件内容
		Blob blob = personalWorkReportAttach.getAttachmentCont();
		//获得InputStream
		InputStream inputStream = blob.getBinaryStream();
		byte[] buffer = new byte[1024];
		int ch;
		//OutPotStream
		ByteArrayOutputStream out= new ByteArrayOutputStream();
		//下面将BLOB数据写入文件
		String str = new String(buffer,"iso-8859-1");
		String str2 = new String(str.getBytes("utf-8"),"iso-8859-1");
		byte buffers[] = str2.getBytes();
		while((ch = inputStream.read(buffer))>0){
			out.write(buffers,0,ch);
		}
		//依次关闭
		out.close();
		inputStream.close();
		return new ByteArrayInputStream(out.toByteArray());  
	}

 Struts.xml的配置

    <!-- 附件下载 -->
    <package name="downloadAttach" namespace="/downloadAttach" extends="struts-default">
    	<action name="assignWork_*" class="AssignWorkAction" method="{1}">
    		 <result name="success" type="stream">
                 <param name="inputName">inputStream</param>  
                 <param name="contentDisposition">attachment;filename="${attachmentFileName}"</param>
                 <param name="bufferSize">4096</param>  
   			 </result>
    	</action>
    </package>

 下载附件功能完成!!