文件上传
前端部分
<div class="cb-item"> <label><em>*</em>班课封面:</label> <div class="inputDiv height140"> <input type="hidden" id="cover"/> <div class="add_pic"><img id="cover-img" src="/assets/flippedClassroom/images/add_pic.jpg" /> <a href="javascript:;" class="upload-img btn-upload-cover"></a></div> <p>图片尺寸宽250px,高170px</p> </div> </div> <script src="/assets/js/jquery-1.11.3.min.js"></script> <script type="text/javascript" charset="utf-8" src="/scripts/plupload/plupload.full.min.js"></script> <script type="text/javascript" charset="utf-8" src="/assets/js/uploader.js"></script> <script type="text/javascript"> $(function(){ //文件上传 $(".upload-img").InitUploader({ btntext:"添加封面", water: false, filesize: "10240", sendurl: "/tools/big_upload", swf: "/scripts/webuploader/uploader.swf", filetypes: "jpg,jpeg,png", success:function(parentObj, data){ if(data.status==1){ $("#cover").val(data.path); $("#cover-img").attr("src","${weburl}" + data.path); Suctan.Box.tip({ msg: data.msg, style: 1 }); }else{ Suctan.Box.tip({ msg: data.msg, style: 2 }); } } }); }) </script>
后端java版
package com.suctan.education.controller.tools; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.suctan.common.HttpUploadFile; import com.suctan.common.JsonHelper; import com.suctan.common.Plupload; import com.suctan.common.PluploadService; import com.suctan.common.PropertiesUtil; import com.suctan.common.Utils; import com.suctan.common.controller.BaseController; import com.suctan.education.model.SiteConfig; import com.suctan.education.service.impl.SiteConfigServiceImpl; @Controller @Scope("prototype") @RequestMapping("/tools") public class BigUploadController extends BaseController { @Autowired private PluploadService pluploadService; @Autowired private SiteConfigServiceImpl siteconfigService; protected HttpServletRequest request; protected HttpServletResponse response; private SiteConfig siteConfig; @RequestMapping(value="/big_upload") public void processRequest(Plupload plupload, HttpServletRequest request, HttpServletResponse response) throws IOException { this.request = request; this.response = response; this.siteConfig = siteconfigService.loadConfig(); plupload.setRequest(request); /*Users userModel = null; String userNid = ""; if (session.getAttribute(STKeys.SESSION_ADMIN_INFO)!= null) { userModel = (Users)session.getAttribute(STKeys.SESSION_ADMIN_INFO); } if (userModel != null) { userNid = userModel.getNid(); }*/ //fileChunkSaveAs(plupload, userNid); fileChunkSaveAs(plupload, "1"); } //region BigFileUpLoad /** * 文件上传方法 * @param plupload:文件流 * @return 上传后文件信息 */ public boolean fileChunkSaveAs(Plupload plupload, String userNid) { try { // 检查客户端已上载的单独文件是否存在 /*if (postedFile == null) { WriteErrorResponse("{\"status\": 0, \"msg\": \"没有文件!\"}"); return false; }*/ //region 记录文件信息并检查是否合法 long fileSize = request.getContentLength();//.getMultipartFile().getSize();// postedFile.ContentLength; //文件大小,以字节为单位 String fileName = plupload.getName(); //文件名称 String fileExt; //文件扩展名,不包含“.” //规范化文件名称,以避免目录遍历的攻击 (normalize file name to avoid directory traversal attacks) fileName = Utils.GetFileName(fileName); fileExt = Utils.GetFileExt(fileName); //检查文件扩展名是否合法 if (!CheckFileExt(fileExt)) { response.getWriter().write("{\"status\": 0, \"msg\": \"不允许上传" + fileExt + "类型的文件!\"}"); return false; } //检查文件大小是否超出限制 if (!CheckFileSize(fileExt, fileSize)) { response.getWriter().write("{\"status\": 0, \"msg\": \"文件超过限制的大小!\"}"); return false; } //endregion int chunks = plupload.getChunks(); if (chunks > 0 && !CheckFileSize(fileExt, fileSize)) { response.getWriter().write("{\"status\": 0, \"msg\": \"文件超过允许大小,无法上传!\"}"); return false; } //String newFileName = "" + System.currentTimeMillis() + "." + fileExt; //文件上传成功后的新文件名 //String newPath = GetUpLoadPath();//文件上传成功后保存的相对路径 String temp = Utils.GetMapPath("/upload/temporary/"+userNid); Utils.DirCreate(temp); File temDir = new File(temp); //临时文件夹路径 //File dir = new File(Utils.GetMapPath(newPath)); //文件保存路径 //开始上传文件 0:失败,1:文件完整上传成功,2:文件块上传成功,3:没有上传文件 Map<String, Object> ret = pluploadService.upload(plupload, temDir); if ((int)ret.get("status") == 3) { response.getWriter().write("{\"status\": 0, \"msg\": \"请选择要上传文件!\"}"); return false; } else if ((int)ret.get("status") == 2) { response.getWriter().write("{\"status\": 0, \"msg\": \"文件块上传成功!\"}"); return false; } else if ((int)ret.get("status") == 0) { response.getWriter().write("{\"status\": 0, \"msg\": \"失败!\"}"); return false; } //模拟浏览器客户端上传视频文件 String url = PropertiesUtil.getValue("apiUrl") + "bigUpload"; Map<String, String> textMap = new HashMap<String, String>(); //可以设置多个input的name,value textMap.put("fileName", fileName); textMap.put("token", token); //设置file的name,路径 Map<String, String> fileMap = new HashMap<String, String>(); fileMap.put("__source", temp + "/" + fileName); String contentType = ""; String returnStr = HttpUploadFile.formUpload(url, textMap, fileMap,contentType); retModel retModel = new retModel(); retModel = JsonHelper.JsonToBean(retModel, returnStr); //处理完毕,返回JOSN格式的文件信息 Map<String, Object> map = new LinkedHashMap<String, Object>(); map.put("status", 1); map.put("msg", "上传文件成功!"); map.put("name", fileName); map.put("size", fileSize); map.put("ext", fileExt); map.put("path", retModel.filePath); response.getWriter().write(JsonHelper.ObjectToJson(map)); return true; } catch(IOException ex) { //response.getWriter().write("{\"status\": 0, \"msg\": \"上传过程中发生意外错误!\"}"); return false; } } //region 私有方法 /** * 检查是否为合法的上传文件 * @param _fileExt * @return */ private boolean CheckFileExt(String _fileExt) { //检查危险文件 String[] excExt = { "asp", "aspx", "ashx", "asa", "asmx", "asax", "php", "jsp", "htm", "html" }; for (int i = 0; i < excExt.length; i++) { if (excExt[i].equalsIgnoreCase(_fileExt)) { return false; } } //检查合法文件 String[] allowExt = (this.siteConfig.getFileExtension() + "," + this.siteConfig.getVideoExtension()).split(","); for (int i = 0; i < allowExt.length; i++) { if (allowExt[i].equalsIgnoreCase(_fileExt)) { return true; } } return false; } /** * 检查文件大小是否合法 * @param _fileExt:文件扩展名,不含“.” * @param _fileSize:文件大小(B) * @return */ private boolean CheckFileSize(String _fileExt, long _fileSize) { //将视频扩展名转换成String[] String[] lsVideoExt = this.siteConfig.getVideoExtension().toLowerCase().split(","); /*//判断是否为图片文件 if (IsImage(_fileExt)) { if (this.siteConfig.getImgSize() > 0 && _fileSize > this.siteConfig.getImgSize() * 1024) { return false; } } else */ if (lsVideoExt.equals(_fileExt.toLowerCase())) { if (this.siteConfig.getVideoSize() > 0 && _fileSize > this.siteConfig.getVideoSize() * 1024) { return false; } } else { if (this.siteConfig.getAttachSize() > 0 && _fileSize > this.siteConfig.getAttachSize() * 1024) { return false; } } return true; } //endregion }