springMvc---跨服務器文件上傳(實測總結)
阿新 • • 發佈:2018-09-18
options color mon alt EDA and serve rip dom
序言:
該案例是采用springMvc實現跨服務器圖片上傳功能,其中用到的主要類和工具有:CommonsMultipartResolver、jquery.form.js。如果要實現多個文件上傳,只需要在input元素中加入multiple="multiple",即可選擇多個文件進行上傳。另外本文的上傳的文件路徑不是在tomcat下對應的文件夾中,而是在workspace對應的文件夾中存在。該案例使用ajax上傳頁面不刷新,多個圖片可立即回顯,並將其相對路徑可以隨著表單一起保存到數據庫中,而文件則存放在文件服務器中。還有,點擊選擇,選擇了文件之後,文件是依附於form表單,因此在使用jquery.form.js的$("#formId").ajaxSubmit(options)提交的表單,提交之後,文件是以流的形式通過HttpServeltRequest傳遞到Controller當中,之後再通過向下強轉成HttpServeltRequest的實現接口MultipartHttpServletRequest進一步獲取到文件集合。
代碼:
springMvc-servlet.xml文件中需要配置:
<!-- 文件上傳解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="20180000"></property> </bean>
jsp頁面:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.js"></script> <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.form.js"></script> <script type="text/javascript"> functionfileOnchage(){ var option = { type:"post", data:{myUploadFile:‘uploadFile‘}, dataType:"string", url:"${pageContext.request.contextPath }/uploadController/upload.do", success:function(data){ //String格式json,轉json對象 var json = $.parseJSON(data); //將對象轉String格式的json(例如數組) //JSON.stringify(‘obj‘); for(var i in json){ $("#picImg").append(‘<img id="myImg" src="‘+json[i].fullPath+‘"/>‘); } } } $("#fileForm").ajaxSubmit(option); } </script> </head> <body> <form id="fileForm" method="post"> <div id="picImg"></div> <input type="file" name="uploadFile" value="請選擇" multiple="multiple" onchange="fileOnchage()"/> <input type="hidden" id="relativePath" value=""> </form> </body> </html>
controller:
package com.cissst.it; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import net.sf.json.JSONArray; import org.springframework.stereotype.Controller; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartFile; import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; @Controller @RequestMapping("/uploadController") public class UploadController { @InitBinder protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws ServletException { binder.registerCustomEditor(CommonsMultipartFile.class, new ByteArrayMultipartFileEditor()); } @RequestMapping("upload") @ResponseBody public String upload(String myUploadFile,HttpServletRequest request){ //多部件請求對象 MultipartHttpServletRequest mh = (MultipartHttpServletRequest) request; //獲取文件list集合 List<MultipartFile> files = mh.getFiles(myUploadFile); //創建jersey服務器,進行跨服務器上傳 Client client = Client.create(); //json格式的圖片路徑 List<String> listJsonPath = new ArrayList<String>(); for (MultipartFile file : files) { String newFileName=""; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); newFileName = sdf.format(new Date()); Random r = new Random(); //{‘‘:‘‘} String jsonPath=""; for(int i =0 ;i<3;i++){ newFileName=newFileName+r.nextInt(10); } //原始的文件名 String originalFilename = file.getOriginalFilename(); //截取文件擴展名 String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")); //絕對路徑(另一臺服務器文件路徑) String fullPath="http://127.0.0.1:8083/springMvc_fileServler/upload/"+newFileName+suffix; //相對路徑(數據庫中存放的文件名) String relativePath=newFileName+suffix; //各自的流 InputStream inputStream = null; try { inputStream = file.getInputStream(); } catch (IOException e1) { e1.printStackTrace(); } //將文件傳入文件服務器 WebResource resource = client.resource(fullPath); resource.put(String.class, inputStream); jsonPath = "{\"fullPath\":\""+fullPath+"\",\"relativePath\":\""+relativePath+"\"}"; listJsonPath.add(jsonPath); } JSONArray jsonArray = JSONArray.fromObject(listJsonPath); return jsonArray.toString(); } }
服務器信息:
master server‘s and point :
file server‘s and point:
you must confrim two server‘s point diffrence
上傳後的文件:
頁面回顯:
springMvc---跨服務器文件上傳(實測總結)