ssh和ajax上传文件

ssh3中利用ajaxfileupload无刷新上传文件

开源中国
开源中国
发表于 2014-09-03 20:29:18

1.jsp代码:(    注意这里的jquery只能用1.2.1,我试了1.3.2会报错:(         )

<%@ 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">

<link rel="stylesheet"href="../js/ajaxfileupload/ajaxfileupload.css"type="text/css"title='main' media="screen"/>


<script src="../js/json.js"type="text/javascript"></script>
<script src="../js/ajaxfileupload/jquery.js"type="text/javascript"></script>
<script src="../js/ajaxfileupload/ajaxfileupload.js"type="text/javascript"></script>

<title>haha</title>
</head>
<body>
<form action=""enctype="multipart/form-data">

<input type="file"name="upload"id="upload"/><input type="button"value="upload"οnclick="javascript:upload_files();"/><p/>
</form>
<img id="loading"src="../images/loading.gif"style="display:none;"/>
</body>

<script>




function upload_files(){


$("#loading")


.ajaxStart(function(){



$(this).show();


})


.ajaxComplete(function(){



$(this).hide();


});





$.ajaxFileUpload


(



{




url:'../demo/test!ajax_upload?id=1',




secureuri:false,




fileElementId:'upload',




dataType: 'json',




success: function (data, status)
{
 alert( data.resultText);
 alert( data.extra );
},
 error: function (data, status, e)
{
alert(e);
}




}


)

}


</script>

</html>

 

 

action代码:

package com.prl.action.demo;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.convention.annotation.ParentPackage;
import org.json.JSONObject;
import org.springside.modules.web.struts2.Struts2Utils;

import com.prl.action.BaseAction;
import com.prl.common.CommonUtil;
import com.prl.helper.JsonResult;

@ParentPackage(value="noneedlogin")
public class TestAction extends BaseAction{

private File upload;

private String uploadFileName;

private String uploadUploadContentType;

private Long id ;

public String ajax_demo(){


HttpServletRequest request = Struts2Utils.getRequest();


CommonUtil.printAllParam(request);





System.out.println("jsonString==============="+request.getParameter("toJSONString"));





JsonResult jsonResult = new JsonResult("0","成功");


Struts2Utils.renderText(new JSONObject(jsonResult).toString());





return null;

}



public String ajax_upload(){


System.out.println("id========="+id);


System.out.println("uploadFileName========="+uploadFileName);


JsonResult jsonResult = new JsonResult("0","成功");





//前台的ajax.upload.js框架可能有bug,导致这个地方必须用renderHtml,不能用其它的


Struts2Utils.renderHtml(new JSONObject(jsonResult).toString());


//Struts2Utils.renderText(new JSONObject(jsonResult).toString());


//Struts2Utils.renderJson(jsonResult);


return null;

}


public File getUpload() {


return upload;

}


public void setUpload(File upload) {


this.upload = upload;

}


public String getUploadFileName() {


return uploadFileName;

}


public void setUploadFileName(String uploadFileName) {


this.uploadFileName = uploadFileName;

}


public String getUploadUploadContentType() {


return uploadUploadContentType;

}


public void setUploadUploadContentType(String uploadUploadContentType) {


this.uploadUploadContentType = uploadUploadContentType;

}


public Long getId() {


return id;

}


public void setId(Long id) {


this.id = id;

}

}

----------------------------------------------------------------------------------------------

SSH总结(二)

1、文件的操作,读写文件,解决乱码问题

读文件

1
2
3
4
5
6
7
InputStreamReader isr =  new  InputStreamReader( new  FileInputStream( new  File(path)),  "UTF-8" );
BufferedReader reader =  new  BufferedReader(isr);
String s;
while  ((s = reader.readLine()) !=  null ) {
     content += s +  "\n" ;
}
reader.close();

 写文件

1
2
3
Writer writer =  new  BufferedWriter( new  OutputStreamWriter( new  FileOutputStream(newFile1.getAbsolutePath().toString()),  "UTF-8" ));
writer.write(content);
writer.close();

 2、struts2常用标签

单选框:<s:radio name="Gender" list="#{'男':'男','女':'女'}" listKey="key" listValue="value" value="'男'" />

时间格式化:<s:date name="publishTime" format="yyyy年MM月dd日 HH:mm:ss" />

下拉框: <s:select list="#request.role" name="role1" value="roleName" key="id" headerKey="0" headerValue="清选择角色"></s:select>

3、ajax上传文件

ajax上传文件主要是使用了ajaxfileupload.js插件,ajax代码如下所示:

 HTMl代码:

1
2
< input  id="fileToUpload" type="file" size="20" name="myFile" class="input">
< button  type="button" id="buttonUpload" data-dismiss="modal" class="btn btn-primary">上传</ button >

 js代码:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
$( "#buttonUpload" ).click( function () {
     //验证图片格式
     var  format = $( "#fileToUpload" ).val();
     var  type = format.substring(format.lastIndexOf( "." ) + 1, format.length).toLowerCase();
     onsole.info(format);
     console.info(type);
     if  (type !=  "jpg"  && type !=  "jpeg"  && type !=  "bmp"  && type !=  "gif"  && type !=  "png" ) {
         alert( "请上传正确的图片格式" );
         return ;
     }
     $.ajaxFileUpload({
         url :  'notice_AddImage.action' , //处理图片脚本
         ecureuri :  false ,
         fileElementId :  'fileToUpload' , //file控件id
         dataType :  'text' ,
         success :  function (data) {
             $( "#dd" ).html(data);
             var  value = $( "#dd pre" ).html();
             if  (value ==  "undefined"  || value ==  null ) {
                 value = data;
             }
             console.info( "dd:"  + value);
             $( "#btn_image" ).val(value);
                 console.info( "image:"  + $( "#btn_image" ).val());
                 $( "#tooltip" ).html( "图片导入成功" );
             },
             error :  function (data) {
                 $( "#dd" ).val(data);
                 console.info( "error" );
                 alert( "error" );
         }
     });
});

  

java代码:

 

复制代码
 1 // myFile属性用来封装上传的文件
 2     private File myFile;
 3 
 4     // myFileContentType属性用来封装上传文件的类型
 5     private String myFileContentType;
 6 
 7     // myFileFileName属性用来封装上传文件的文件名
 8     private String myFileFileName;
 9     InputStream is;
10         try {
11             is = new FileInputStream(myFile);
12             // 设置上传文件目录
13             String uploadPath = TemplateUtils.BASEPATH + "\\upload";
14             // 重命名文件
15             String fileName = StringUtils.getUUID() + this.getMyFileFileName().substring(myFileFileName.lastIndexOf("."), myFileFileName.length());
16             // 设置目标文件
17             File toFile = new File(uploadPath, fileName);
18             // 创建一个输出流
19             OutputStream os = new FileOutputStream(toFile);
20             // 设置缓存
21             byte[] buffer = new byte[1024];
22             int length = 0;
23             // 读取myFile文件输出到toFile文件中
24             while ((length = is.read(buffer)) > 0) {
25                 os.write(buffer, 0, length);
26             }
27             // 关闭输入流
28             is.close();
29             // 关闭输出流
30             os.close();

      
---------------------------------------------------------------------------------------------

      

JQuery和Struts实现Ajax文件上传

首先说下使用的框架和插件:

struts1.3   jQuery1.3   ajaxupload.3.2.js(一个JQuery的插件,实现Ajax上传的效果)

COS(O’relly的一个性能很棒的上传组件)

jsp页面:

<%@ page language="java"  pageEncoding="UTF-8"%>
<%@ include file="../../common/taglibs.jsp" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  	<script type="text/javascript" src="${basePath }/script/jquery.js"></script>
  	<script type="text/javascript" src="${basePath }/script/ajaxupload.3.2.js"></script>
    <title>Ajax文件上传示例</title>
    <style type="text/css">
    	#loading,ol{
    		font-size:14px;
    		display:none;
    		color:orange;
    		display:none;
    	}
    	ol{
    		display:block;
    	}
    </style>
	<script type="text/javascript">
		$(function(){
			
			new AjaxUpload("#fileButton",{
				action:"${basePath}/file.do?method=upload",
				autoSubmit:true,
				name:"myfile",
				onSubmit:function(file, extension){
					if (extension && /^(pdf|jpg|png|jpeg|gif)$/.test(extension))
					{
						$("#loading").html('<img src="${basePath}/images/loading.gif">');
						$("#loading").show();
						$("#fileButton").attr("disabled","disabled");
					}
					else
					{
						$("#loading").html("你所选择的文件不受系统支持");
						$("#loading").show();
						return false;
					}
				},
				onComplete:function(file, extension){
					$("#loading").html("文件上传成功");
					$("#loading").show();
					$("#fileButton").removeAttr("disabled");
				}
			});
			
			
			new Ajax_upload('#button3', {
				action: '${basePath}/file.do?method=upload',
				name: 'myfile',
				autoSubmit:true,
				onComplete : function(file, extension){
					$('<li></li>').appendTo($('.files')).text(file);
				}	
			});
		});
	</script>
  </head>
  
  <body> 
    <input type="button" value="请选择您的照片" id="fileButton"/>
    <div id="loading"><img src="${basePath}/images/loading.gif"></div>
    <hr/>
   
    <form action="#" method="post">

		<input id="button3" type="file" />
		<p>上传成功的文件有:</p>
		<ol class="files"></ol>
		<p>
			<input class="submit" type="submit" value="表单提交"/>	
		</p>

	</form>

  </body>
</html>
StrutsAction代码:
package com.kay.crm.web;

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

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.springframework.stereotype.Controller;

import com.kay.common.util.CosUtil;

@Controller("/file")
public class FileUploadAction extends DispatchAction {

	public ActionForward upload(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		

		String fileName = CosUtil.upload(request);
		System.out.println(fileName);
		
		return null;
	}
}
Cos的工具类:
package com.kay.common.util;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import com.oreilly.servlet.MultipartRequest;

public class CosUtil {

	@SuppressWarnings({ "deprecation", "unchecked" })
	public static String upload(HttpServletRequest request) throws IOException
	{
		//存绝对路径
		//String filePath = "C://upload";
		//存相对路径
		String filePath = request.getRealPath("/")+"upload";
		File uploadPath = new File(filePath);
		//检查文件夹是否存在 不存在 创建一个
		if(!uploadPath.exists())
		{
			uploadPath.mkdir();
		}
		//文件最大容量 5M
		int fileMaxSize = 5*1024*1024;
	
		//文件名
		String fileName = null;
		//上传文件数
		int fileCount = 0;
		//重命名策略
		RandomFileRenamePolicy rfrp=new RandomFileRenamePolicy();
		//上传文件
		MultipartRequest mulit = new MultipartRequest(request,filePath,fileMaxSize,"UTF-8",rfrp);
		
		String userName = mulit.getParameter("userName");
		System.out.println(userName);
		
		Enumeration filesname = mulit.getFileNames();
	      while(filesname.hasMoreElements()){
	           String name = (String)filesname.nextElement();
	           fileName = mulit.getFilesystemName(name);
	           String contentType = mulit.getContentType(name);
	           
	           if(fileName!=null){
	        	   fileCount++;
	           }
	           System.out.println("文件名:" + fileName);
	           System.out.println("文件类型: " + contentType);
	           
	      }
	      System.out.println("共上传" + fileCount + "个文件!");
	      
	      return fileName;
	}
}
Cos上传组件用到的重命名策略类:
package com.kay.common.util;

import java.io.File;
import java.util.Date;

import com.oreilly.servlet.multipart.FileRenamePolicy;

public class RandomFileRenamePolicy implements FileRenamePolicy {

	public File rename(File file) {
	  String body="";
      String ext="";
      Date date = new Date();
      int pot=file.getName().lastIndexOf(".");
      if(pot!=-1){
          body= date.getTime() +"";
          ext=file.getName().substring(pot);
      }else{
          body=(new Date()).getTime()+"";
          ext="";
      }
      String newName=body+ext;
      file=new File(file.getParent(),newName);
      return file;

	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值