nutz 前台如何上传多个图片文件,后台如何接收
@Wizzercn 有相关连接信息,谢谢
<div class="controls">
<input type="file" name="pic" style="display: none;"
onchange="CheckFile1(this)" id="lefile1"
accept=".jpg, .png, .mp4,.avi" />
<div class="input-append">
<input id="photoCover1"
onkeyup="this.value='';$('[name=pic]').val('')"
style="width: 100%" type="text"
placeholder="文件大小需小于 10M"> <a class="btn"
onclick="$('input[id=lefile1]').click();">选择文件1</a>
</div>
</div>
<div class="controls">
<input type="file" name="pic" style="display: none;"
onchange="CheckFile2(this)" id="lefile2"
accept=".jpg, .png, .mp4,.avi" />
<div class="input-append">
<input id="photoCover2"
onkeyup="this.value='';$('[name=pic]').val('')"
style="width: 100%" type="text"
placeholder="文件大小需小于 10M"> <a class="btn"
onclick="$('input[id=lefile2]').click();">选择文件2</a>
</div>
</div>
var url = "${ctx}/property/addstandby/" + s;
//var url = "${ctx}/property/addstandby/";
if (submit_flag) {//js 防止表单提交,
ajaxFileUpload(url, form);
submit_flag = false;
} else {
return;
}
}
//ajax上传文件
function ajaxFileUpload(url, form) {
$.ajaxFileUpload({
url : url, //用于文件上传的服务器端请求地址
secureuri : false, //是否需要安全协议,一般设置为false
fileElementId : [ 'lefile', 'lefile1', 'lefile2' ],//文件上传域的ID
data : form,
type : 'POST',
dataType : 'JSON', //返回值类型 一般设置为json
success : adCallback,
error : function(data, status, e)//服务器响应失败处理函数,成功也是指向error
{
adCallback(data);
}
});
return false;
}
@At("/addstandby/?")
@Ok("json")
@AdaptBy(type = UploadAdaptor.class, args = { "ioc:myUpload" })
public Object addstandby(String type, @Param("..") Tbl_ad_plan plan,
@Param("ad_area_desc") String area_desc,
@Param("price_info") String price_info,
@Param("charge_ad_fee") Integer charge_ad_fee,
@Param("fee_way") Integer fee_way,
@Param("period_month") Integer period_month,
@Param("gift_month") Integer gift_month,
@Param("pic_url") String pic_url, @Param("pic") TempFile tf,
@Param("pic") TempFile[] tf1,
jQuery.extend({
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
if(window.ActiveXObject)
{
if(typeof uri== 'boolean'){
iframeHtml += ' src="' + 'javascript:false' + '"';
}
else if(typeof uri== 'string'){
iframeHtml += ' src="' + uri + '"';
}
}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body);
return jQuery('#' + frameId).get(0);
},
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>');
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
/***** 增加参数的支持 *****/
if (data) {
for (var i in data) {
$('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').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;
},
ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime();
// ADD s.data
var form = jQuery.createUploadForm(id, s.fileElementId, s.data);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if ( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// Process result
if ( s.complete )
s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function()
{ try
{
jQuery(io).remove();
jQuery(form).remove();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if(form.encoding)
{
jQuery(form).attr('encoding', 'multipart/form-data');
}
else
{
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
jQuery('#' + frameId).load(uploadCallback );
return {abort: function () {}};
},
/** handleError 方法在jquery1.4.2之后移除了,此处重写改方法 **/
handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error ) {
s.error.call( s.context || s, xhr, status, e );
}
// Fire the global callback
if ( s.global ) {
(s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
}
},
uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" ){
jQuery.globalEval( data );
}
// Get the JavaScript object, if JSON is used.
if ( type == "json" ){
/*** 如果返回的是字符串(JSON格式字符串),下面会报错,导致无法走入sucess方法 加上\" ***/
// eval( "data = " + data );
eval("data = \" "+data+" \" ");
}
// evaluate scripts within html
if ( type == "html" ){
jQuery("<div>").html(data).evalScripts();
}
return data;
}
})
@wendal 我按照这个修改了,还有传过去是一个文件
2018-05-23 21:06:07> <WARN> [org.nutz.mvc.impl.processor.FailProcessor] - Erro@/property/addstandby/10, :
java.lang.ClassCastException: java.util.LinkedList cannot be cast to org.nutz.mvc.upload.TempFile
at org.nutz.mvc.upload.injector.TempFileInjector.get(TempFileInjector.java:22)
at org.nutz.mvc.upload.injector.TempFileInjector.get(TempFileInjector.java:1)
at org.nutz.mvc.adaptor.AbstractAdaptor.adapt(AbstractAdaptor.java:219)
at org.nutz.mvc.impl.processor.AdaptorProcessor.process(AdaptorProcessor.java:28)
at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
at org.nutz.mvc.impl.processor.ActionFiltersProcessor.process(ActionFiltersProcessor.java:40)
at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
at org.nutz.mvc.impl.processor.ModuleProcessor.process(ModuleProcessor.java:99)
at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
at org.nutz.mvc.impl.processor.EncodingProcessor.process(EncodingProcessor.java:27)
at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
at org.nutz.mvc.impl.processor.UpdateRequestAttributesProcessor.process(UpdateRequestAttributesProcessor.java:15)
at org.nutz.mvc.impl.NutActionChain.doChain(NutActionChain.java:40)
at org.nutz.mvc.impl.ActionInvoker.invoke(ActionInvoker.java:64)
at org.nutz.mvc.ActionHandler.handle(ActionHandler.java:31)
at org.nutz.mvc.NutFilter.doFilter(NutFilter.java:94)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:722)
@At("/addstandby/?")
@Ok("json")
@AdaptBy(type = UploadAdaptor.class, args = { "ioc:myUpload" })
public Object addstandby(String type, @Param("..") Tbl_ad_plan plan,
@Param("ad_area_desc") String area_desc,
@Param("price_info") String price_info,
@Param("charge_ad_fee") Integer charge_ad_fee,
@Param("fee_way") Integer fee_way,
@Param("period_month") Integer period_month,
@Param("gift_month") Integer gift_month,
@Param("pic_url") String pic_url, @Param("pic") TempFile tf,
@Param("pic") TempFile[] tf1,
@wendal 还是延续昨天情况,上传到服务器多个图片路径读的是第一个路径?
嗯呢,,http://test.xboxes.cn:80/eop/images/takeTurnsImages/1527169415310.jpg,http://test.xboxes.cn:80/eop/images/takeTurnsImages/1527169415310.jpg
private String saveImage(TempFile tf, HttpServletRequest req, String folder) {
File f = tf.getFile();
String fileName = f.getName();
// 获得后缀名
String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
// 最终重命名图片的名称
String targeName = System.currentTimeMillis() + "." + prefix;
// 保存图片名称到记录
// 获得当前项目的路径
String realPath = req.getSession().getServletContext().getRealPath("/");
com.ruyima.util.FileUtils.moveFile(f, realPath + folder + targeName);
return targeName;
}