ajax上传文件springmvc
Ⅰ 求解Spring mvc 文件上传采用jquery插件 AjaxFileUpload.js 出现的一些问题
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>checkbox</title>
<script src="js/jquery-1.3.2.js" type="text/javascript"></script>
<script src="js/1.js" type="text/javascript"></script>
</head>
<body>
<table id="table1">
<tr>
<td><input type="checkbox" value="1"/>1</td>
<td id="k_1"><input type="text" name="student" id="s_1" readonly="true"/></td>
</tr>
<tr>
<td><input type="checkbox" value="2"/>2</td>
<td id="k_2"><input type="text" name="student" id="s_2" readonly="true"/></td>
</tr>
<tr>
<td><input type="checkbox" value="3"/>3</td>
<td id="k_3"><input type="text" name="student" id="s_3" readonly="true"/></td>
</tr>
<tr>
<td><input type="checkbox" value="4"/>4</td>
<td id="k_4"><input type="text" name="student" id="s_4" readonly="true"/></td>
</tr>
</table>
</body>
</html>
-------------------------------------------------------------
$(document).ready(function() {
$("td[id^='k_']").hide();
var check = $(":checkbox"); //得到所有被选中的checkbox
var actor_config; //定义变量
check.each(function(i){
actor_config = $(this);
actor_config.click(
function(){
if($(this).attr("checked")==true){
$("#k_"+$(this).val()).show();
}else{
$("#k_"+$(this).val()).hide();
}
}
);
});
});
Ⅱ 怎么用ajax实现上传文件的功能
HTTP File Server
http-file-server是用 python 实现的 HTTP 文件服务器,支持上传和下载文件。
运行
$ python file-server.py files 8001
其中第一个参数files是存放文件的路径,第二个参数8001是 HTTP 服务器端口。
接口
1. 读取文件
GET /pathtofile/filename
2. 读取文件夹下所有文件(已经忽略隐藏文件)
GET /path
返回文件列表为JSON数组,文件名末尾带有/的表示是文件夹。filename为文件名,mtime为修改时间。
[{"filename":"f1.txt","mtime":1001},{"filename":"p3/","mtime":1002}]
3. 上传文件
采用POST方式上传文件,URL参数中传参数name表示上传的文件名,POST内容为文件内容。
POST /upload?name=filename
ajax示例:
// file is a FileReader object
var data = file.readAsArrayBuffer();
var xhr = new XMLHttpRequest();
var url = "http://localhost:8001/upload?name=xxx.md";
xhr.open("post", url, true);
xhr.setRequestHeader("Accept", "application/json, text/javascript, */*; q=0.01");
xhr.onreadystatechange = function() {
if (xhr.readyState==4 && xhr.status==200)
{
console.log(xhr.responseText);
}
}
xhr.send(data);
文件名 filename 可以包含相对路径。比如:upload?name=md/xxx.md。则上传至md目录下。
Ⅲ SpringMVC,ajax,怎么传递带List的复杂的参数啊
着重看看 #{isReaded} 和 collection="messageIds",这里也是跟 Java 实体类逐个对应,十分称心。
值得一说的是 ,郑滚它主要就是用来构建 in() 条件。
- item 表示集合中每一个元素进行迭代时的别名
- index 指定一个名字,用于表示在迭代过程中,每次迭代到的位置
- open 表示该语句以什么开始
- separator 表示在每次进行迭代之间以什么符号作为分隔符
- close 表示以什么结束
其中在指定“collection”属性时比较容易出错:
- 如果传入的是单参数且参数类型是一个 List 的时候,collection 属性值为 list
- 如果传入的是单参数且参数类型是一个 array 数组的时候,collection的 属性值为 array
foreach 元素的属性主要有软件开发尘滑公司http://www.yingtaow.com?item、index、collection、open、separator、close。
```javascript
viewMessage: function (messageId) {
console.info('viewMessage');
// 通过 id 获取完整数据对象
var message = $.grep($messageDatagrid.datagrid('getRows'), function (n, i) {
return n.messageId == messageId
})[0];
console.info(message);
// 如果该条记喊兄余录是“未读”则更新为“已读”
if (message.isReaded == YesOrNoEnum.No) {
var updateReadState = {
isReaded: YesOrNoEnum.Yes,
messageIds: [messageId]
}; $.ajax({
data: JSON.stringify(updateReadState),
url: UrlEnum.UpdateReadState,
type: "POST",
dataType: "json",
contentType: 'application/json;charset=utf-8', //“参数为泛型集合 @RequestBody List<> 时”需设置请求头信息
success: function (result) {
console.info('updateReadState success,返回数据如下:↓');
console.info(result);if (result.success) {
$.messager.show({
title: '提示', // 头部面板上显示的标题文本。
msg: result.message
});$messageDatagrid.datagrid('load');
// 确保没有任何缓存痕迹(必不可少)
$messageDatagrid.datagrid('clearChecked');
$messageDatagrid.datagrid('clearSelections');
}
else {
if (result.operationType == operationTypeEnum.CookieTimeout) {
result.message = decodeURIComponent(result.message);
}
$.messager.alert('提示', result.message, 'warning');
}
},
error: function (result) {
}
}); // end ajax
} // isReaded = no
}
```
在传递复杂类型的数据时,注意 Ajax 方法的 data 和 contentType 两个参数的设置。在 data 属性中用到了 JSON.stringify(),目的是将 data 属性转化为“JSON字符文本”形式,也是防止 jQuery 内部把 data 属性转化成了“查询字符串”格式(key1=valu1&key2=value2),倘若如此 SpringMVC 就不好识别解析了。
## Java 实体类
```javascript
public class BaseMessageUpdateReadState extends BaseEntity {
private List messageIds;
private IntegerisReaded;public List getMessageIds() {
return messageIds;
}public void setMessageIds(List messageIds) {
this.messageIds = messageIds;
}public Integer getIsReaded() {
return isReaded;
}public void setIsReaded(Integer isReaded) {
this.isReaded = isReaded;
}
}
```
该实体类就是一个复杂形式的实体类,把实体类 BaseMessageUpdateReadState 的字段与客户端的 JSON 对象 updateReadState 作比较,可见二者是如此一致,需注意一下的是 js 中的数组与 Java 中的泛型集合 List 相对应。
## 控制器
```javascript
@RequestMapping(value = "/UpdateReadState", method = RequestMethod.POST)
@ResponseBody
public TransactionResult UpdateReadState(@RequestBody BaseMessageUpdateReadState baseMessageUpdateReadState, @CookieValue(value = "base_cookieKey", required = false) CookieObject cookieObject) {
baseMessageUpdateReadState.setCookieObject(cookieObject);
TransactionResult result = null;
try {
result = iBaseMessageService.UpdateReadState(baseMessageUpdateReadState);
return result;
} catch (RuntimeException e) {
result = new TransactionResult(false);
if (e.getMessage() == null) {
ByteArrayOutputStream buf = new java.io.ByteArrayOutputStream();
e.printStackTrace(new java.io.PrintWriter(buf, true));
String expMessage = buf.toString();
try {
buf.close();
} catch (IOException e1) {
e1.printStackTrace();
}
result.setMessage(expMessage);
} else {
result.setMessage(e.getMessage());
}
return result;
}
}
```
在控制器方法中,参数 BaseMessageUpdateReadState 前面必须带上 @RequestBody,它负责将 JSON 格式的复杂参数转化为 Java 实体类,非常的方便。
## MyBatis 应用
接口:
```javascript
int affectedRows = iBaseMessageDao.UpdateReadState(baseMessageUpdateReadState);
```
XML映射器:
```javascript
Update BaseMessage
Set
IsReaded = #{isReaded}
Where 1=1
and MessageId in
#{item}
```
Ⅳ ajax如何 实现 文件上传
程序说明
使用说明
实例化时,第一个必要参数是file控件对象:
newQuickUpload(file);
第二个可选参数用来设置系统的默认属性,包括
属性: 默认值//说明
parameter:{},//参数对象
action:"",//设置action
timeout:0,//设置超时(秒为单位)
onReady:function(){},//上传准备时执行
onFinish:function(){},//上传完成时执行
onStop:function(){},//上传停止时执行
onTimeout:function(){}//上传超时时执行
还提供了以下方法:
upload:执行上传操作;
stop:停止上传操作;
dispose:销毁程序。
varQuickUpload=function(file,options){
this.file=$$(file);
this._sending=false;//是否正在上传
this._timer=null;//定时器
this._iframe=null;//iframe对象
this._form=null;//form对象
this._inputs={};//input对象
this._fFINISH=null;//完成执行函数
$$.extend(this,this._setOptions(options));
};
QuickUpload._counter=1;
QuickUpload.prototype={
//设置默认属性
_setOptions:function(options){
this.options={//默认值
action:"",//设置action
timeout:0,//设置超时(秒为单位)
parameter:{},//参数对象
onReady:function(){},//上传准备时执行
onFinish:function(){},//上传完成时执行
onStop:function(){},//上传停止时执行
onTimeout:function(){}//上传超时时执行
};
return$$.extend(this.options,options||{});
},
//上传文件
upload:function(){
//停止上一次上传
this.stop();
//没有文件返回
if(!this.file||!this.file.value)return;
//可能在onReady中修改相关属性所以放前面
this.onReady();
//设置iframe,form和表单控件
this._setIframe();
this._setForm();
this._setInput();
//设置超时
if(this.timeout>0){
this._timer=setTimeout($$F.bind(this._timeout,this),this.timeout*1000);
}
//开始上传
this._form.submit();
this._sending=true;
},
//设置iframe
_setIframe:function(){
if(!this._iframe){
//创建iframe
variframename="QUICKUPLOAD_"+QuickUpload._counter++,
iframe=document.createElement($$B.ie?"<iframename=""+iframename+"">":"iframe");
iframe.name=iframename;
iframe.style.display="none";
//记录完成程序方便移除
varfinish=this._fFINISH=$$F.bind(this._finish,this);
//iframe加载完后执行完成程序
if($$B.ie){
iframe.attachEvent("onload",finish);
}else{
iframe.onload=$$B.opera?function(){this.onload=finish;}:finish;
}
//插入body
varbody=document.body;body.insertBefore(iframe,body.childNodes[0]);
this._iframe=iframe;
}
},
//设置form
_setForm:function(){
if(!this._form){
varform=document.createElement('form'),file=this.file;
//设置属性
$$.extend(form,{
target:this._iframe.name,method:"post",encoding:"multipart/form-data"
});
//设置样式
$$D.setStyle(form,{
padding:0,margin:0,border:0,
backgroundColor:"transparent",display:"inline"
});
//提交前去掉form
file.form&&$$E.addEvent(file.form,"submit",$$F.bind(this.dispose,this));
//插入form
file.parentNode.insertBefore(form,file).appendChild(file);
this._form=form;
}
//action可能会修改
this._form.action=this.action;
},
//设置input
_setInput:function(){
varform=this._form,oldInputs=this._inputs,newInputs={},name;
//设置input
for(nameinthis.parameter){
varinput=form[name];
if(!input){
//如果没有对应input新建一个
input=document.createElement("input");
input.name=name;input.type="hidden";
form.appendChild(input);
}
input.value=this.parameter[name];
//记录当前input
newInputs[name]=input;
//删除已有记录
deleteoldInputs[name];
}
//移除无用input
for(nameinoldInputs){form.removeChild(oldInputs[name]);}
//保存当前input
this._inputs=newInputs;
},
//停止上传
stop:function(){
if(this._sending){
this._sending=false;
clearTimeout(this._timer);
//重置iframe
if($$B.opera){//opera通过设置src会有问题
this._removeIframe();
}else{
this._iframe.src="";
}
this.onStop();
}
},
//销毁程序
dispose:function(){
this._sending=false;
clearTimeout(this._timer);
//清除iframe
if($$B.firefox){
setTimeout($$F.bind(this._removeIframe,this),0);
}else{
this._removeIframe();
}
//清除form
this._removeForm();
//清除dom关联
this._inputs=this._fFINISH=this.file=null;
},
//清除iframe
_removeIframe:function(){
if(this._iframe){
variframe=this._iframe;
$$B.ie?iframe.detachEvent("onload",this._fFINISH):(iframe.onload=null);
document.body.removeChild(iframe);this._iframe=null;
}
},
//清除form
_removeForm:function(){
if(this._form){
varform=this._form,parent=form.parentNode;
if(parent){
parent.insertBefore(this.file,form);parent.removeChild(form);
}
this._form=this._inputs=null;
}
},
//超时函数
_timeout:function(){
if(this._sending){this._sending=false;this.stop();this.onTimeout();}
},
//完成函数
_finish:function(){
if(this._sending){this._sending=false;this.onFinish(this._iframe);}
}
}
Ⅳ dojo ajax 怎样上传文件到spring mvc 控制层
虚拟一个form表单,然后提交这个表单即可
Ⅵ ajaxfileupload+springmvc上传多文件的control怎么写
1.Spring mvc
a.xml配置:
[html] view plain print?
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<!-- set the max upload size1MB 1048576 -->
<property name="maxUploadSize">
<value>52428800</value>
</property>
<property name="maxInMemorySize">
<value>2048</value>
</property>
</bean>
b. 服务器端接收解析
[java] view plain print?
public void imgUpload(
MultipartHttpServletRequest multipartRequest,
HttpServletResponse response) throws Exception {
response.setContentType("text/html;charset=UTF-8");
Map<String, Object> result = new HashMap<String, Object>();
//获取多个file
for (Iterator it = multipartRequest.getFileNames(); it.hasNext();) {
String key = (String) it.next();
MultipartFile imgFile = multipartRequest.getFile(key);
if (imgFile.getOriginalFilename().length() > 0) {
String fileName = imgFile.getOriginalFilename();
//改成自己的对象哦!
Object obj = new Object();
//Constant.UPLOAD_GOODIMG_URL 是一个配置文件路径
try {
String uploadFileUrl = multipartRequest.getSession().getServletContext().getRealPath(Constant.UPLOAD_GOODIMG_URL);
File _apkFile = saveFileFromInputStream(imgFile.getInputStream(), uploadFileUrl, fileName);
if (_apkFile.exists()) {
FileInputStream fis = new FileInputStream(_apkFile);
} else
throw new FileNotFoundException("apk write failed:" + fileName);
List list = new ArrayList();
//将obj文件对象添加到list
list.add(obj);
result.put("success", true);
} catch (Exception e) {
result.put("success", false);
e.printStackTrace();
}
}
}
String json = new Gson().toJson(result,
new TypeToken<Map<String, Object>>() {
}.getType());
response.getWriter().print(json);
}
//保存文件
private File saveFileFromInputStream(InputStream stream, String path,
String filename) throws IOException {
File file = new File(path + "/" + filename);
FileOutputStream fs = new FileOutputStream(file);
byte[] buffer = new byte[1024 * 1024];
int bytesum = 0;
int byteread = 0;
while ((byteread = stream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
fs.flush();
}
fs.close();
stream.close();
return file;
}
2.关于前端代码
a.修改ajaxfileupload.js
先到官网下载该插件.
将源文件的createUploadForm的代码替换如下:
[javascript] view plain print?
createUploadForm: function(id, fileElementId, data)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
if (data) {
for ( var i in data) {
jQuery(
'<input type="hidden" name="' + i + '" value="'
+ data[i] + '" />').appendTo(form);
}
}
for (var i = 0; i < fileElementId.length; i ++) {
var oldElement = jQuery('#' + fileElementId[i]);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileElementId[i]);
jQuery(oldElement).attr('name', fileElementId[i]);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
}
//set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
}
第一步高定
b. 页面代码
html:
[html] view plain print?
<input type="button" value="添加附件" onclick="createInput('more');" />
<div id="more"></div>
js:这里可以专门写封装类,以及给file加onchange事件判断文件格式。由于时间有限,未修改
[javascript] view plain print?
var count = 1;
/**
* 生成多附件上传框
*/
function createInput(parentId){
count++;
var str = '<div name="div" ><font style="font-size:12px;">附件</font>'+
' '+ '<input type="file" contentEditable="false" id="uploads' + count + '' +
'" name="uploads'+ count +'" value="" style="width: 220px"/><input type="button" value="删除" onclick="removeInput(event)" />'+'</div>';
document.getElementById(parentId).insertAdjacentHTML("beforeEnd",str);
}
/**
* 删除多附件删除框
*/
function removeInput(evt, parentId){
var el = evt.target == null ? evt.srcElement : evt.target;
var div = el.parentNode;
var cont = document.getElementById(parentId);
if(cont.removeChild(div) == null){
return false;
}
return true;
}
下面是2个修改多file用的js,用于显示和删除,可以于上面的合并精简代码:
[javascript] view plain print?
function addOldFile(data){
var str = '<div name="div' + data.name + '" ><a href="#" style="text-decoration:none;font-size:12px;color:red;" onclick="removeOldFile(event,' + data.id + ')">删除</a>'+
' ' + data.name +
'</div>';
document.getElementById('oldImg').innerHTML += str;
}
function removeOldFile(evt, id){
//前端隐藏域,用来确定哪些file被删除,这里需要前端有个隐藏域
$("#imgIds").val($("#imgIds").val()=="" ? id :($("#imgIds").val() + "," + id));
var el = evt.target == null ? evt.srcElement : evt.target;
var div = el.parentNode;
var cont = document.getElementById('oldImg');
if(cont.removeChild(div) == null){
return false;
}
return true;
}
ajax上传文件:
[javascript] view plain print?
function ajaxFileUploadImg(id){
//获取file的全部id
var uplist = $("input[name^=uploads]");
var arrId = [];
for (var i=0; i< uplist.length; i++){
if(uplist[i].value){
arrId[i] = uplist[i].id;
}
}
$.ajaxFileUpload({
url:'xxxxx',
secureuri:false,
fileElementId: arrId, //这里不在是以前的id了,要写成数组的形式哦!
dataType: 'json',
data: {
//需要传输的数据
},
success: function (data){
},
error: function(data){
}
});
}
Ⅶ spring mvc上传怎么用ajax
准备工作:
前端引入:1、jquery,我在这里用的是:jquery-1.10.2.min.js
2、ajaxfileupload.js
这里可能会报一些错,所以在json判断那里修改为(网上也有):
Js代码
if ( type == "json" ){
data = r.responseText;
var start = data.indexOf(">");
if(start != -1) {
var end = data.indexOf("<", start + 1);
if(end != -1) {
data = data.substring(start + 1, end);
}
}
eval( "data = " + data );
}
末尾那里补充一段:
Js代码
handleError: function( s, xhr, status, e ) {
if ( s.error ) {
s.error.call( s.context || window, xhr, status, e );
}
if ( s.global ) {
(s.context ? jQuery(s.context) : jQuery.event).trigger ( "ajaxError", [xhr, s, e] );
}
}
后台导入spring的jar包,我这里用的是:spring3.0.5
在spring.xml里配置如下:
Xml代码
<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<!-- 不在这里限制了,后台各自进行限制了
<property name="maxUploadSize" value="2000000"/>
-->
</bean>
<!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart. -->
<!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.">
<property name="exceptionMappings">
<props>
<!-- 遇到异常时,跳转到/page/html/errorGolbal.html页面 -->
<prop key="org.springframework.web.multipart.">/page/html/errorGolbal.html</prop>
</props>
</property>
</bean>
这里就充分利用框架的便利性帮你都做好了,如果你不在xml里配置这些,
那么在controller那里,request.getInputStream()得到的这个流不全是文件流,还包含了其他,需要你自己编码去解析,当
然,要解析的话还要知道http相关报文解析知识,所以这里可以充分利用框架的便利性,有兴趣的可以研究下
好了,准备工作做好了,看下前端的具体代码:
Html代码
<div id="fileUpLoad" class="manage">
添附文件
<!-- 自定义 <input type="file"/> -->
<input type="file" id="btnFile" name="btnFile" onchange="txtFoo.value=this.value;com.company.project.services.newCase.fileUpLoad()" hidden="hidden" />
<input type="text" id="txtFoo" readonly="readonly" style="width: 300px" />
<button onclick="btnFile.click()" style="height: 25px;">选择文件</button>
</div>
js代码为:
Js代码
if (!window.com) {
window.com = {};
}
if (!window.com.company) {
window.com.company= {};
}
if (!window.com.company.project) {
window.com.company.project= {};
}
if (!window.com.company.project.services) {
window.com.company.project.services = {};
}
if (!window.com.company.project.services.newCase) {
window.com.company.project.services.newCase = {};
}
//生成随机guid数(参考网上)
com.company.project.services.newCase.getGuidGenerator = function() {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
};
//上传文件
com.company.project.services.newCase.fileUpLoad = function(){
var fileName = $("#btnFile").val();//文件名
fileName = fileName.split("\\");
fileName = fileName[fileName.length-1];
var guid = com.company.project.services.newCase.getGuidGenerator();//唯一标识guid
var data = {guid:guid};
jQuery.ajaxSettings.traditional = true;
$.ajaxFileUpload({
url : '/PROJECT/function.do?method=fileUpLoad',
secureuri : false,//安全协议
fileElementId:'btnFile',//id
type : 'POST',
dataType : 'json',
data:data,
async : false,
error : function(data,status,e) {
alert('Operate Failed!');
},
success : function(json) {
if (json.resultFlag==false){
alert(json.resultMessage);
}else{
alert('文件上传成功!');
var next = $("#fileUpLoad").html();
$("#fileUpLoad").html("<div id='"+guid+"'>"+"文件:"+fileName+" <a href='#' onclick='com.company.project.services.newCase.filedelete("+"\""+guid+"\""+","+"\""+fileName+"\""+")'>删除</a>"+"<br/></div>");
$("#fileUpLoad").append(next);
}
}
});
};
//文件删除
com.company.project.services.newCase.filedelete = function(guid,fileName){
jQuery.ajaxSettings.traditional = true;
var data = {guid:guid,fileName:fileName};
$.ajax({
url : '/PROJECT/function.do?method=filedelete',
type : 'POST',
dataType : 'json',
data:data,
async : false,
error : function() {
alert('Operate Failed!');
},
success : function(json) {
if (json.resultFlag==false){
alert(json.resultMessage);
}else{
alert('删除成功!');
$("#"+guid).remove();
}
}
});
};
----------------------------------------------------------------------------------
注:如果你对ajax不熟悉,或者由于浏览器等原因,致使上述方式提交出现各种问题,那么你可以用form表单形式提交,代码片段如下:
Html代码
<div id="fileUpLoad" class="manage">
<form id="needHide" action="/工程/function.do?method=fileUpLoad" method="post" enctype="multipart/form-data" target = "hidden_frame">
<!-- 自定义 <input type="file"/> -->
<input type="file" id="btnFile" name="btnFile" onchange="txtFoo.value=this.value;com.company.project.services.newCase.fileUpLoad()" hidden="hidden"/>
</form>
添附文件
<input type="text" id="txtFoo" readonly="readonly" style="width: 300px" />
<button onclick="btnFile.click()" style="height: 25px;">选择文件</button>
<iframe name='hidden_frame' id="hidden_frame" style='display: none' onload="com.company.project.services.newCase.statusCheck()"></iframe>
</div>
js代码写为:
Js代码
var flag = true;
com.company.project.services.newCase.statusCheck = function(){
if(flag == false){
var status = hidden_frame.window.document.getElementById("hideForm").innerHTML;
console.log(status);
}
flag = false;
};
//上传文件
com.company.project.services.newCase.fileUpLoad = function(){
$("#needHide").submit();
}
后台代码主要在最后变为:
Java代码
PrintWriter printWriter = response.getWriter();
printWriter.write("<div id='hideForm'>1111</div>");
----------------------------------------------------------------------------------
后台对应java代码段为:
Java代码
@RequestMapping(params = "method=fileUpLoad")
//btnFile对应页面的name属性
public void fileUpLoad(@RequestParam MultipartFile[] btnFile, HttpServletRequest request, HttpServletResponse response){
try{
//文件类型:btnFile[0].getContentType()
//文件名称:btnFile[0].getName()
if(btnFile[0].getSize()>Integer.MAX_VALUE){//文件长度
OutputUtil.jsonArrOutPut(response, JSONArray.fromObject("上传文件过大!"));
}
InputStream is = btnFile[0].getInputStream();//多文件也适用,我这里就一个文件
//String fileName = request.getParameter("fileName");
String guid = request.getParameter("guid");
byte[] b = new byte[(int)btnFile[0].getSize()];
int read = 0;
int i = 0;
while((read=is.read())!=-1){
b[i] = (byte) read;
i++;
}
is.close();
OutputStream os = new FileOutputStream(new File("D://"+guid+"."+btnFile[0].getOriginalFilename()));//文件原名,如a.txt
os.write(b);
os.flush();
os.close();
OutputUtil.jsonOutPut(response, null);
}catch (Exception e) {
OutputUtil.errorOutPut(response, "系统异常");
}
}
@RequestMapping(params = "method=filedelete")
public void filedelete(HttpServletRequest request, HttpServletResponse response){
try{
String guid = request.getParameter("guid");
String fileName = request.getParameter("fileName");
File file = new File("D://"+guid+"."+fileName);
boolean isDeleted = file.delete();
if(!isDeleted){
OutputUtil.errorOutPut(response, "文件删除失败");
}
OutputUtil.jsonArrOutPut(response, null);
}catch (Exception e) {
OutputUtil.errorOutPut(response, "系统异常");
}
}
另外:如果是图片上传的话,你也可以不保存在什么临时目录,可以用base64进行编解码,网上也有很多,简单介绍下:
后台只要这么做:
Java代码
//得到byte数组后
BASE64Encoder base64e = new BASE64Encoder();
JSONArray ja = new JSONArray();
String base64Str = base64e.encode(b);
ja.add(base64Str);
OutputUtil.jsonArrOutPut(response, JSONArray.fromObject(ja));
前台页面只要这么就可以拿到了:
Html代码
$("#fileUpLoad")
.append("<image src='"+"data:image/gif;base64,"+json.resultMessage[0]+"' >");
对于json相关不大了解的可以参考我的博文:
http://quarterlifeforjava.iteye.com/blog/2024336
效果和iteye的相似:
补充:如果要让表单提交后还是留在当前页面,除了Ajax还可以用iframe,代码如下:
其实关键就是iframe和form中的target
Ⅷ springmvc怎么接受ajax发送过来的文件
你文件上传用的什么方式
如果是submit直接提交的需要给form加一个属性:enctype="multipart/form-data"
如果是异步提交则需要看你的上传控件的ID是否正确
Ⅸ springmvc+ajax上传图片的问题。传过去的是空值.怎么接收图片
因为SpringMVC只有GET请求才能通过方法上加参数获取到值,POST是不能通过这种方式获取的,可以通过request.getParameter(key) 或者 封装成对象(属性对应前端参数)会自动填充。
另外我记得Ajax上传文件不能直接用$.ajax这种方式传,我的方法如下:
var form = new FormData();
var xhr = new XMLHttpRequest();
xhr.open("post", "url", true);
xhr.onload = function () {
alert("上传完成!");
};
xhr.send(form);
Ⅹ springmvc怎么用ajax传一个对象数组
参考代码如下:
var as = [];
var temp = [];
for ( var int = 0; int <禅毁 5; int++) {
temp.push('{"k":');
temp.push(int);
temp.push(',"v":');
temp.push(int);
temp.push('雀袭誉}');
as.push(temp.join(""));
}
//Jquery中的方法,具顷段体参考Jquery API
$.post(
"servlet/AjaxServlet?m=putWarningRule",{"aa":as}
);