NutzCN Logo
问答 nutz 前台如何上传多个图片文件,后台如何接收
发布于 2367天前 作者 qq_e3b6dba3 2255 次浏览 复制 上一个帖子 下一个帖子
标签:

nutz 前台如何上传多个图片文件,后台如何接收

57 回复

@Wizzercn 有相关连接信息,谢谢

日志贴一下看看

前端用表单直接提交的吗?有没有用第三方js库做提交?

<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>

这是前台页面

前端用表单直接提交的吗?有没有用第三方js库做提交?

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,

哪一款ajaxFileUpload?

后端这样写的

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

})

这是里面代码

var oldElement = jQuery('#' + fileElementId);

它不支持多个文件的

大神,你有支持的方式么?

小弟,我也不太懂

没太理解,把这方法加入到js中么?

把链接看完, 新版jquery有很多办法

@wendal 我按照这个修改了,还有传过去是一个文件

for (var i in fileElementId)

它有这句, 会全部加进去的样子

如果你搞不定,那就得分开来测试嘛

先另外写个页面,用直接提交的方式,不走ajax,确保前后台能跑通

然后再去试ajax方式,这时候后台是好的,避免两线作战

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)

谁有空看看,这是报错日志

@Param("pic") Object tfs

然后打印一下tfs是什么东西

@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,

这是后台写的

改成

@Param("pic") Object tfs

然后打印一下tfs是什么内容

改一下就肯定能进后台啦,把业务代码统统注释掉

[org.nutz.mvc.upload.TempFile@3b9ff2, org.nutz.mvc.upload.TempFile@81f412]

打印是这东西

目测被坑, 这样写...

@Param("pic") List<TempFile> tfs

[org.nutz.mvc.upload.TempFile@1527383, org.nutz.mvc.upload.TempFile@1da657]

这是修改完打印的

嗯, 应该就能用了 -_- 能拿到2个TemFile了

PS: nutz版本多少,最后这个坑得查查

大神,怎么看版本?

我这也是接着人家做

maven的话看pom.xml,p普通javaee项目的看lib目录

话说,启动的时候有打印的

Nutz Version : 1.b.49.r2 2013-09-11

@wendal 还是延续昨天情况,上传到服务器多个图片路径读的是第一个路径?

没看懂,啥意思

后端已经拿到两个TempFile对象了吧?

嗯呢,,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;
}

按照获取不同文件名称

我是本地测试代码,没问题。上传到linux服务器上,操作数据库里插入就是系统文件路径名

System.currentTimeMillis() 还不是时间戳?

服务器速度够快,一毫秒处理完两个文件也很正常啊

谢谢你,我加了uuid,才好使!

添加回复
请先登陆
回到顶部