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}
);