300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > jQuery插件之ajaxFileUpload上传文件或图片

jQuery插件之ajaxFileUpload上传文件或图片

时间:2022-09-29 15:14:14

相关推荐

jQuery插件之ajaxFileUpload上传文件或图片

我用的是这个:/carlcarl/AjaxFileUpload

下载地址在这里:/files/kissdodog/ajaxfileupload_JS_File.rar

AjaxFileUpload.js并不是一个很出名的插件,只是别人写好的放出来供大家用,原理都是创建隐藏的表单和iframe然后用JS去提交,获得返回值。

当初做了个异步上传的功能,选择它因为它的配置方式比较像jQuery的AJAX,我很喜欢。

ajaxFileUpload是一个异步上传文件的jQuery插件

语法:$.ajaxFileUpload([options])

options参数说明:

1、url 上传处理程序地址。

2、fileElementId 需要上传的文件域的ID,即的ID。

3、secureuri 是否启用安全提交,默认为false。

4、dataType 服务器返回的数据类型。可以为xml,script,json,html。如果不填写,jQuery会自动判断。

5、success提交成功后自动执行的处理函数,参数data就是服务器返回的数据。

6、error 提交失败自动执行的处理函数。

7、data 自定义参数。这个东西比较有用,当有数据是与上传的图片相关的时候,这个东西就要用到了。

8、type 当要提交自定义参数时,这个参数要设置成post

使用方法:

第一步:先引入jQuery与ajaxFileUpload插件。注意先后顺序,这个不用说了,所有的插件都是这样。

<script src="jquery-1.7.1.js" type="text/javascript"></script><script src="ajaxfileupload.js" type="text/javascript"></script>

第二步:HTML代码:

<div id="sys" class="col-md-4" style="margin-top: 25px;"><div class="tab-pane fade in active" id="systemConfig" ><form id="photoUploadForm"><div class="input-group"><span class="input-group-addon">项目名称:</span><input type="text" name="name" id="name" value="${sysConfig.name}" class="form-control"></div><div style="background: #6ccac9;margin-top: 20px;padding: 10px;"><span style="margin: 15px;">当前项目Logo</span> <span style="margin-left: 50px;">添加图片预览</span><div class="input-group" ><image src="${sysConfig.images}" name="img" style="height: 80px;width: 80px; margin:20px;" alt="点击图片更换系统LOGO" /><image id="chooseImg" onclick="replaceLogo()" src="/static/images/addImg.jpg" value="" style="height: 80px;width: 80px;margin-left: 50px;" /><input type="hidden" id="photoUrl" name="images" value=""/></div></div><div class="input-group"><p><input type="file" style="display: none;" onchange="inputChange(this)" id="uploadFile" name="uploadFile" accept="image/png,image/gif,image/jpg,image/jpeg" /></p><input type="button" class="btn btn-primary" value="保存" onclick="shangchuan()" style="margin-top: 25px;" /></div></form></div></div>

第三步:JS代码

//当输入框的值发生改变时触发时间,预览图片必须用change事件,且change事件在HTML页面绑定,在js中绑定change事件第二次上传的时候不能预览,这是由于ajaxFileUpload插件克隆input组件导致的function inputChange(e){$.ajaxFileUpload({url: '/update/ajaxFileUpload', //用于文件上传的服务器端请求地method:"post",secureuri: false, //是否需要安全协议,一般设置为falsefileElementId: 'uploadFile', //文件上传域的IDdataType: 'json',//返回值类型 一般设置为jsonsuccess: function (d) //服务器成功响应处理函数{if(d.state=="success"){$("#chooseImg").attr("src",d.url);$("#photoUrl").attr("value",d.url);}}})}//点击添加图片打开上传文件的窗口function replaceLogo() {$("#uploadFile").click();}

第四步:后台FileUploadController代码:

package com.metro.crm.controller.base.controller;import com.metro.crm.service.system.SettingService;import mons.logging.Log;import mons.logging.LogFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.util.FileCopyUtils;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.multipart.MultipartHttpServletRequest;import javax.annotation.Resource;import javax.imageio.ImageIO;import javax.servlet.ServletContext;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.awt.*;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.HashMap;import java.util.Map;/*** 本地上传* [@author](/arthor)**/[@Controller](/u/1774615)@RequestMappingpublic class FileUploadController{private static final Log logger = LogFactory.getLog(FileUploadController.class);/** 上传文件名 */private static final String UPLOAD_FILE_NAME = "uploadFile";/*** 前端获取服务器绝对路径图片* [@param](/u/2303379) fileName* [@param](/u/2303379) response*/@RequestMapping(value = "/update/getImg", method = RequestMethod.GET)public void getImg(String fileName , HttpServletResponse response){File f = new File(fileName);try {String file = fileName.substring(fileName.lastIndexOf("/")+1,fileName.length());Image image = ImageIO.read(f);if(image == null){String fileExt = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length()).toLowerCase();response.setContentType("application/octet-stream;");response.setHeader("Content-Disposition", "attachment;fileName="+file);}FileCopyUtils.copy(new FileInputStream(f), response.getOutputStream());} catch (IOException e) {// TODO 自动生成的 catch 块e.printStackTrace();}}@ResponseBody@RequestMapping(value = "/update/ajaxFileUpload", method = RequestMethod.POST)public Map<String,Object> ajaxFileUpload(HttpServletRequest request, HttpServletResponse response){MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;MultipartFile uploadFile = multipartRequest.getFile(UPLOAD_FILE_NAME);Map<String, Object> map = new HashMap<String, Object>();if (uploadFile == null) {map.put("status", "error");map.put("message", "上传失败:文件为空");return map;}try {//1.文件存储在临时目录上String fileName = uploadFile.getOriginalFilename();//获取上传文件类型的扩展名,先得到.的位置,再截取从.的下一个位置到文件的最后,最后得到扩展名String fileExt = fileName.substring(fileName.lastIndexOf("."),fileName.length()).toLowerCase();SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");String newName = sdf.format(new Date());//获取当前项目根目录String path = request.getSession().getServletContext().getRealPath("");File filePath=new File(path);path = filePath.getParentFile().getParent()+"/upload";//获取文件夹位置(用作判断文件夹是否存在)File file =new File(path);//如果文件存在,则删除文件夹下面的文件,保证文件夹中只有当前上传的一张图片,上传多张的则不需要这个判断if(file .exists()){File[] files = file.listFiles();for (int i = 0; i < files.length; i++) {if (files[i].isFile()){File photoFile = new File(files[i].getPath());photoFile.delete();}}}//如果文件夹不存在则创建if (!file .exists() && !file .isDirectory()){//创建upload目录file.mkdir();}//把图片放在项目根目录的上一级目录(防止系统更新导致文件丢失)path+= "/"+newName+fileExt;//前端获取绝对路径图片path=path.replace("\\","/");String frontImg = "/update/getImg?fileName="+path;File f = new File(path);//保存到指定目录uploadFile.transferTo(f);map.put("state", "success");map.put("message","上传成功" );//返回给kindEditormap.put("url",frontImg );return map;} catch (IOException e) {String msg = "上传文件失败:"+e.getMessage();logger.info("=========="+msg);map.put("state", "error");map.put("message",msg );return map;}}}

项目运行效果图:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。