加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ajax无刷新上传(使用ajaxfileupload.js)

发布时间:2020-12-16 01:54:31 所属栏目:百科 来源:网络整理
导读:body input type="file" id="files" name="files" onchange="javascript: ajaxFileUpload()" class="transparent_class"/ input type="button" value="上传" / pimg id="img1" alt="上传成功啦" src="" width="135px" height="101px"//p/bodyscript type="te
<body>
    <input type="file" id="files" name="files"  onchange="javascript: ajaxFileUpload()" class="transparent_class"/>
    <input type="button" value="上传" />
    <p><img id="img1" alt="上传成功啦" src="" width="135px" height="101px"/></p>
</body>
<script type="text/javascript">
        $(function () {
            $(":button").click(function () {
                ajaxFileUpload();
            })
        })
        
        function ajaxFileUpload() {
            $.ajaxFileUpload
            (
                {
                    url: '${ctx}/ajaxUploadFile.html',//用于文件上传的服务器端请求地址
                    secureuri: false,//是否需要安全协议,一般设置为false
                    fileElementId: 'files',//文件上传域的ID
                    dataType: 'json',//返回值类型 一般设置为json
                    success: function (data,status)  //服务器成功响应处理函数
                    {
                        /*alert(data); //可以查看返回的值*
                        $("#img1").attr("src","${ctx }/upload/" + data);
                    	
                        if (typeof (data.error) != 'undefined') {
                            if (data.error != '') {
                                alert(data.error);
                            } else {
                                alert(data.msg);
                            }
                        }
                    },error: function (data,status,e)//服务器响应失败处理函数
                    {
                    	$("#img1").attr("src","${ctx }/images/pictureFile.jpg");
                        alert(e);
                    }
                }
            )
            return false;
        }
    </script>


mvc后台:
controller:

package com.langtai.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSON;
import com.langtai.service.UploadService;
@Controller
public class UploadController {
	@Autowired
	UploadService UploadService;
	
	@RequestMapping(value="ajaxUploadFile.html",method=RequestMethod.POST)
	public void AjaxUpload(@RequestParam MultipartFile[] files,HttpServletResponse response,HttpServletRequest request) throws IOException{
		System.out.println("收到" + files.length  + "个上传的请求");
		//WEB-INF/upload在服务器中默认的地址
		String realPath = request.getSession().getServletContext().getRealPath("/upload");
		List<String> fileNames = UploadService.upload(files,realPath);
		String jsonFileNames = JSON.toJSONString(fileNames);
		System.out.println(jsonFileNames);
		PrintWriter out = response.getWriter();
		out.print(jsonFileNames);
		out.flush();
		out.close();
	}
}

service:

package com.langtai.service;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@Service
public class UploadService {
	public List<String> upload(MultipartFile[] files,String realPath) {
		//上传的文件的原名
		String originalFilename = null;
		List<String> fileNames = new ArrayList<String>();
		int i = 0;
		
		for (MultipartFile multipartFile : files) {
			if(multipartFile.getSize()==0)
				continue;
			originalFilename = multipartFile.getOriginalFilename();
			System.out.println("文件的原名:"  + originalFilename);
			System.out.println("文件的名称:"  + multipartFile.getName());
			System.out.println("文件的长度:"  + multipartFile.getSize());
			System.out.println("文件的类型:"  + multipartFile.getContentType());
			System.out.println("==============================================");
			try {
				String[] Filetype = originalFilename.split(".");
				String newFileName = new Date().getTime()  + (i++) + "." + Filetype[Filetype.length-1];
				fileNames.add(newFileName);
				FileUtils.copyInputStreamToFile(multipartFile.getInputStream(),new File(realPath,newFileName));
			} catch (IOException e) {
				System.out.println("文件" + originalFilename + "上传失败,堆栈轨迹如下:");
				e.printStackTrace();
			}
		}
		return fileNames;
	}
}

------------------------------------------------------------------------------------------------------------------------------------------
该插件对于json的处理有误,解析json会出错,所以:

修改源码,将

if ( type == "json" )
eval_r( "data = " + data );

改成:

if ( type == "json" ){
data = jQuery.parseJSON(jQuery(data).text());
}
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
在1.4以上jq中没有了handleError这个函数,所以可以把这个函数添加进这个插件中最上面去:


handleError: function (s,xhr,e) {

        if (s.error) {

            s.error.call(s.context || s,e);

        }

        if (s.global) {

            (s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError",[xhr,s,e]);

        }

    },httpData: function (xhr,type,s) {

        var ct = xhr.getResponseHeader("content-type"),xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,data = xml ? xhr.responseXML : xhr.responseText;

        if (xml && data.documentElement.tagName == "parsererror")

            throw "parsererror";

        if (s && s.dataFilter)

            data = s.dataFilter(data,type);

        if (typeof data === "string") {

            if (type == "script")

                jQuery.globalEval(data);

            if (type == "json")

                data = window["eval"]("(" + data + ")");

        }

        return data;

    },

------------------------------------------------------------------------------------------------------------------------------------------ 在使用这个插件的时候,<input>中一定要有name属性和id属性,且name属性要和controller中参数名一样。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读