ssh和ajax上传文件
来源:互联网 发布:linux可以ghost吗 编辑:程序博客网 时间:2024/06/04 01:03
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"onclick="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、文件的操作,读写文件,解决乱码问题
读文件
1234567InputStreamReader 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();
写文件
123Writer 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代码:
12<
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代码:
123456789101112131415161718192021222324252627282930313233$(
"#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();}//文件最大容量 5Mint 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;}}
0 0
- ssh和ajax上传文件
- angular上传文件和ajax上传文件
- PHP和AJAX上传文件
- SpringMVC和ajax文件上传
- SSH实现带进度条的Ajax文件上传
- ssh框架下的ajax异步文件上传
- ajax上传文件和csv文件读写
- ssh远程下载和上传文件
- ssh上传和下载linux文件命令
- 文件上传(表单上传和ajax异步上传)
- 7.27--SSH学习之SpringMVC,Ajax请求、拦截器、文件上传和MyBatis访问数据库基本操作
- JQuery和Struts实现Ajax文件上传
- JQuery和Struts实现Ajax文件上传
- Ajax和OSS文件上传、删除
- ajax FormData上传文件和数据
- Ajax的GET与POST和Ajax文件上传进度条
- uploadsample(上传文件和Ajax显示上传进度)
- SSH实现文件上传
- 移动端各屏幕尺寸
- Android开发,调用相册图片或者调用相机进行拍照获取图片
- Android控件之ListView(二)
- respondsToSelector相关的方法
- Java Web开发常问问题 重点概要
- ssh和ajax上传文件
- Android中dp和px之间进行转换
- NFV之OpenWRT IN OpenStack的实践
- 如何在Xamarin中引用原生的AndroidClassLibrary所产生出来的Jar档
- linux socket 设置从哪个网络设备发送数据 SO_BINDTODEVICE
- python学习记录之1027
- ERROR 主机不支持 任意虚拟化选项
- Android 自定义xml中的view。适配
- C++宏定义详解