<div class="input-group">
<input type="file" id="test1" onchange="messageFuncArray.choosefile($(this))" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" multiple/>
<!-- <input type="file" id="test1" onchange="messageFuncArray.choosefile($(this))" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg">-->
<input id="test2" type="button" class="btn btn-default form-control" value="请选择文件" onclick="document.getElementById('test1').click()">
</div>
<button class="btn btn-primary btn-md-2" onclick="messageFuncArray.createNews()">发表</button>
1. 实现js(相关代码可过滤)
var messageFuncArray = { choosefile:function(t){ debugger; var val = t.val(); //t.siblings("img").remove(); // var files = t.get(0).files; this.creactimg(t.get(0).files[0],t); // if(files.length > 1){ // for(var i = 0; i < files.length; i++){ // this.creactimg(t.get(0).files[i],t); // } // }else{ // // } }, createNews: function () { var messageInfo = $('#news').val(); var file = $("#test1").val(); if(!file) { alert("上传图片哦"); return } var fd = new FormData(); // fd.append("file",$("#test1").get(0).files[0]) for(var i = 0; i < filesArray.length; i++){ fd.append("file" + i ,filesArray[i]); } //fd.append("file",$("#test1")); fd.append("messageInfo",messageInfo) fd.append("userId",userId) $.ajax({ url:contextPath + messagePath + '/addMessage', method:"post", // contentType:"multipart/form-data", contentType: false, processData: false, async:false, data:fd, success:function(data){ debugger var dataList = data.dataList, newsFeedItemGrid = $('#newsfeed-items-grid'), articleHtml = ''; articleHtml += '<div class="ui-block display-none">'; articleHtml += toArticleHtml(dataList[0], dataList[1]); articleHtml += commentTextarea(userId, $('#userLogo').attr('src')); articleHtml += '</div>'; debugger; newsFeedItemGrid.prepend(articleHtml); $('#newsfeed-items-grid .ui-block:first-child').show(300); $('.tab-pane').find('textarea').val(''); $("#test1").val(""); $("#test1").siblings("img").remove(); filesArray = []; }, error:function(){ } }) } } function toArticleHtml(user, message) { var img = message.messagePicture.split(","); var imgstr = ""; if(img.length != 0){ for(var i =0; i<img.length-1;i++){ imgstr += "<div><img src=static/img/upload/"+ img[i] +" /></div>"; } } return '<article class="hentry post video">' + '<span class="message-id display-none">' + message.messageId + '</span>' + '<div class="post__author author vcard inline-items">' + '<img src="' + user.userLogo + '" alt="' + user.userId + '">' + '<div class="author-date">' + '<a class="h6 post__author-name fn" href="javascript:void(0)">' + user.userNickname + '</a>' + '<div class="post__date">' + '<time class="published" datetime="2004-07-24T18:18">' + time(message.messageTime) + '</time>' + '</div>' + '</div>' + '<div class="more">' + '<svg class="olymp-three-dots-icon">' + '<use xlink:href="static/svg-icons/sprites/icons.svg#olymp-three-dots-icon"></use>' + '</svg>' + '<ul class="more-dropdown">' + '<li><a href="javascript:void(0)" onclick="messageFuncArray.delMessage($(this))">删除消息</a></li><li><a href="javascript:void(0)" onclick="messageFuncArray.setoursSee('+ message.messageId +')">仅自己可见</a></li>' + '</ul>' + '</div>' + '</div>' + '<p>' + message.messageInfo + '</p>'+ imgstr + '<div class="post-additional-info inline-items">' + '<a href="javascript:void(0)" onclick="messageFuncArray.addCollect($(this))" ' + 'class="post-add-icon inline-items">' + '<svg class="olymp-heart-icon">' + '<use xlink:href="static/svg-icons/sprites/icons.svg#olymp-heart-icon"></use>' + '</svg>' + '<span>' + message.messageCollect + '</span>' + '</a>' + '<div class="comments-shared">' + '<a href="javascript:void(0)" class="post-add-icon inline-items">' + '<svg class="olymp-speech-balloon-icon">' + '<use xlink:href="static/svg-icons/sprites/icons.svg#olymp-speech-balloon-icon"></use>' + '</svg>' + '<span>' + message.messageComment + '</span>' + '</a>' + '</div>' + '</div>' + '<div class="control-block-button post-control-button"></div>' + '</article>'; }
2.Controller层
@RequestMapping(value = "/addMessage") public PageInfo<Object> addMessage(@RequestParam("file") MultipartFile[] file, HttpServletRequest request){ String messageInfo = request.getParameter("messageInfo"); String userId = request.getParameter("userId"); /* String file = request.getParameter("file");*/ List<MultipartFile> listfile = new ArrayList<>(); // MultipartHttpServletRequest multipartHttpServletRequest=(MultipartHttpServletRequest)request; /* MultipartFile file1 = multipartHttpServletRequest.getFile(file);*/ // 转换request,解析出request中的文件 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; // 获取文件map集合 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap(); for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()){ MultipartFile mf = entity.getValue(); listfile.add(mf); } Messages messages = new Messages(); messages.setMessageInfo(messageInfo); messages.setUserId(Integer.parseInt(userId)); return messagesServiceImpl.addMessage(messages, listfile, request); }
3.service层(图片路径需要有webapp文件夹)
@Override public PageInfo<Object> addMessage(Messages messages, List<MultipartFile> listfile, HttpServletRequest request) { if(imgUrl.length()>0){ imgUrl=""; } listfile.forEach(file -> { try { // 图片路径 String resultPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/static/img/upload/"; String userLogoPath = resultPath + messages.getUserId() + "/"; //ResultMap.PROJECT_DIRECTORY+ String uploadImgPath = request.getSession().getServletContext().getRealPath("static/img/upload") + "/" + messages.getUserId() + "/" ; //上传 String filename = upload(file, uploadImgPath, file.getOriginalFilename()); if (filename != null) { imgUrl += new File(uploadImgPath).getName() + "/" + filename + ","; } } catch (Exception e) { e.printStackTrace(); } }); messages.setMessagePicture(imgUrl); messages.setMessageTime(new Date()); messages.setStatus(0);//设置消息为公开 int addResult = messagesMapper.addMessage(messages); List<Object> objs = new ArrayList<>(2); if (addResult > 0) { objs.add(usersMapper.findUserByCondition(new Users(messages.getUserId()))); objs.add(messagesMapper.findMessByUserIdOrderByTime(messages.getUserId())); PageInfo<Object> pageInfo = new PageInfo<>(); pageInfo.setDataList(objs); return pageInfo; } return null; } public String upload(MultipartFile file, String path, String fileName) throws Exception { // 生成新的文件名 String realPath = path + "/" + UUID.randomUUID().toString().replace("-", "")+fileName.substring(fileName.lastIndexOf(".")); File dest = new File(realPath); // 判断文件父目录是否存在 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdir(); } // 保存文件 file.transferTo(dest); return dest.getName(); }
4.返回的实体类:PageInfo<T>
public class PageInfo<T> { private int page; //当前页码 private int limit;//每页显示的数据量 private int dataSize;//数据总数 private List<T> dataList;//数据集 public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } public int getDataSize() { return dataSize; } public void setDataSize(int dataSize) { this.dataSize = dataSize; } public List<T> getDataList() { return dataList; } public void setDataList(List<T> dataList) { this.dataList = dataList; } }