1.android前端發送服務器請求javascript
在spring-mvc.xml 將過濾屏蔽(若是不屏蔽 ,文件流爲空)html
1 <!-- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" 2 p:defaultEncoding="UTF-8"> <property name="maxUploadSize"> <value>2000000000</value> 3 </property> <property name="maxInMemorySize"> <value>2000000000</value> </property> 4 </bean> -->
2.在spring-mvc.xml 中加入請求url:<value>fileUploadController.do?uploads</value> 前端
1 <!-- 攔截器 --> 2 <mvc:interceptors> 3 <mvc:interceptor> 4 <mvc:mapping path="/**" /> 5 <bean class="org.jeecgframework.core.interceptors.EncodingInterceptor" /> 6 </mvc:interceptor> 7 <mvc:interceptor> 8 <mvc:mapping path="/**" /> 9 <bean class="org.jeecgframework.core.interceptors.AuthInterceptor"> 10 <property name="excludeUrls"> 11 <list> 12 <value>loginController.do?goPwdInit</value> 13 <value>loginController.do?pwdInit</value> 14 <value>loginController.do?login</value> 15 <value>loginController.do?checkuser</value> 16 <value>systemController.do?saveFiles</value> 17 <value>systemController.do?saveFilesBeads</value> 18 <value>systemController.do?saveFilesCustomer</value> 19 <value>systemController.do?saveNews</value> 20 <value>iconController.do?saveIcon</value> 21 <value>userController.do?savesign</value> 22 <value>xiNaiInterfaceController.do?interface</value> 23 <value>fileUploadController.do?uploads</value> 24 <value>jpPersonController.do?importExcel</value> <!-- for:[119]excel導入風格統一 --> 25 </list> 26 </property> 27 </bean> 28 </mvc:interceptor> 29 </mvc:interceptors>
3.服務器請求 獲取存儲目錄java
linux服務器沒法再建立目錄,windows能夠多加入tomcat下linux
http://192.168.0.112:8080/properties/fileUploadController.do?uploadsandroid
1 /*** 2 * 文件上傳例子 resource code encoding is utf-8 3 * <br>主要爲了android客戶端實現功能 4 * 5 */ 6 @Controller 7 @RequestMapping("/fileUploadController") 8 public class FileUploadController extends ActionSupport { 9 14 15 @RequestMapping(params = "uploads") 16 public void doPost(HttpServletRequest request, HttpServletResponse response) 17 throws ServletException, IOException 18 { 19 response.setContentType("text/html"); 20 PrintWriter out = response.getWriter(); 21 22 // 建立文件項目工廠對象 23 DiskFileItemFactory factory = new DiskFileItemFactory(); 24 25 // 設置文件上傳路徑 26 //String upload="D:/sinia/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/properties/upload/"; 27 28 String upload = request.getRealPath("/"); 29 // 獲取系統默認的臨時文件保存路徑,該路徑爲Tomcat根目錄下的temp文件夾 30 String temp = System.getProperty("java.io.tmpdir"); 31 // 設置緩衝區大小爲 5M 32 factory.setSizeThreshold(1024 * 1024 * 5); 33 // 設置臨時文件夾爲temp 34 factory.setRepository(new File(temp)); 35 // 用工廠實例化上傳組件,ServletFileUpload 用來解析文件上傳請求 36 ServletFileUpload servletFileUpload = new ServletFileUpload(factory); 37 JSONObject ob = new JSONObject(); 38 // 解析結果放在List中 39 try 40 { 41 List<FileItem> list = servletFileUpload.parseRequest(request); 42 43 for (FileItem item : list) 44 { 45 String name = item.getFieldName(); 46 InputStream is = item.getInputStream(); 47 48 if (name.contains("content")) 49 { 50 System.out.println(inputStream2String(is)); 51 } 52 else if(name.contains("file")) 53 { 54 try 55 { 56 inputStream2File(is, upload + "/" + item.getName()); 57 58 //ob.put("path", upload + "\\" + item.getName()); 59 ob.put("path", upload +item.getName()); 60 out.write(ob.toString()); 61 } catch (Exception e) 62 { 63 e.printStackTrace(); 64 } 65 } 66 } 67 //out.write("success"); 68 } catch (FileUploadException e) 69 { 70 out.write("failure"); 71 } 72 73 out.flush(); 74 out.close(); 75 } 76 // 流轉化成字符串 77 public static String inputStream2String(InputStream is) throws IOException 78 { 79 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 80 int i = -1; 81 while ((i = is.read()) != -1) 82 { 83 baos.write(i); 84 } 85 return baos.toString(); 86 } 87 // 流轉化成文件 88 public static void inputStream2File(InputStream is, String savePath) 89 throws Exception 90 { 91 System.out.println("文件保存路徑爲:" + savePath); 92 File file = new File(savePath); 93 InputStream inputSteam = is; 94 BufferedInputStream fis = new BufferedInputStream(inputSteam); 95 FileOutputStream fos = new FileOutputStream(file); 96 int f; 97 while ((f = fis.read()) != -1) 98 { 99 fos.write(f); 100 } 101 fos.flush(); 102 fos.close(); 103 fis.close(); 104 inputSteam.close(); 105 }
文件存儲目錄 web
D:/sinia/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/propertiesspring
後臺加入上傳功能:jsp上傳文檔:apache
jsp文檔 加入上傳功能json
<script type="text/javascript"> function commonUpload() { $.dialog({ content : "url:xnProjectController.do?uploadprofile", lock : true, title : "圖片上傳", width : 400, height : 100, parent : windowapi, cache : false, zIndex : 9999, ok : function() { var iframe = this.iframe.contentWindow; iframe.uploadCallback(callback); return true; }, cancelVal : '關閉', cancel : function() { } }); } </script>
<td > 上傳文件:</td> <td ><input type="button" onclick="commonUpload()" value="工程進度文檔文件"></td> </tr>
在java控制器上
//上傳文件 @RequestMapping(params = "uploadprofile") public ModelAndView uploadprofile(HttpServletRequest req) { return new ModelAndView("properties/xnUploadFile/uploadfile"); }
uploadfile.jsp
1 <%@ page language="java" pageEncoding="UTF-8"%> 2 <!DOCTYPE HTML> 3 <html> 4 <head> 5 <title>文件上傳</title> 6 </head> 7 <body> 8 <form action="${pageContext.request.contextPath}/servlet/XnUploadFileController" enctype="multipart/form-data" method="post"> 9 上傳文件:<input type="file" name="file"><br/> 10 <input type="submit" value="提交"> 11 </form> 12 </body> 13 </html>
XnUploadFileController.java
1 package jeecg.properties; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.util.List; 8 9 import javax.servlet.ServletException; 10 import javax.servlet.http.HttpServlet; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 14 import jeecg.system.pojo.base.TSDocument; 15 import jeecg.system.service.SystemService; 16 17 import org.apache.commons.fileupload.FileItem; 18 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 19 import org.apache.commons.fileupload.servlet.ServletFileUpload; 20 import org.apache.log4j.Logger; 21 import org.jeecgframework.core.common.model.common.UploadFile; 22 import org.jeecgframework.core.common.model.json.AjaxJson; 23 import org.jeecgframework.core.constant.Globals; 24 import org.jeecgframework.core.util.DataUtils; 25 import org.jeecgframework.core.util.MyBeanUtils; 26 import org.jeecgframework.core.util.MyClassLoader; 27 import org.jeecgframework.core.util.StringUtil; 28 import org.jeecgframework.core.util.oConvertUtils; 29 import org.springframework.beans.factory.annotation.Autowired; 30 import org.springframework.stereotype.Controller; 31 import org.springframework.web.bind.annotation.RequestMapping; 32 import org.springframework.web.bind.annotation.ResponseBody; 33 import org.springframework.web.servlet.ModelAndView; 34 35 import com.jspsmart.upload.SmartUpload; 36 37 38 39 @Controller 40 @RequestMapping("/xnUploadFileController") 41 public class XnUploadFileController extends HttpServlet{ 42 /** 43 * Logger for this class 44 */ 45 private static final Logger logger = Logger.getLogger(XnUploadFileController.class); 46 47 @Autowired 48 private SystemService systemService; 49 private String message; 50 51 public String getMessage() { 52 return message; 53 } 54 55 public void setMessage(String message) { 56 this.message = message; 57 } 58 @RequestMapping(params = "upload") 59 public ModelAndView upload(HttpServletRequest request) { 60 return new ModelAndView("properties/xnUploadFile/uploadfile"); 61 } 62 63 public void doGet(HttpServletRequest request, HttpServletResponse response) 64 throws ServletException, IOException { 65 66 //獲得上傳文件的保存目錄,將上傳的文件存放於WEB-INF目錄下,不容許外界直接訪問,保證上傳文件的安全 67 68 69 /** 70 * 71 * 在server 目錄裏建立upload文件夾 72 * 73 * .metadata\.plugins\org.eclipse.wst.server.core 74 * 75 */ 76 77 String savePath = this.getServletContext().getRealPath("/"); 78 //String savePath ="D:/sinia/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/properties/upload/"; 79 File file = new File(savePath); 80 //判斷上傳文件的保存目錄是否存在 81 if (!file.exists() && !file.isDirectory()) { 82 System.out.println(savePath+"目錄不存在,須要建立"); 83 //建立目錄 84 file.mkdir(); 85 } 86 //消息提示 87 String message = ""; 88 try{ 89 //使用Apache文件上傳組件處理文件上傳步驟: 90 //一、建立一個DiskFileItemFactory工廠 91 DiskFileItemFactory factory = new DiskFileItemFactory(); 92 //二、建立一個文件上傳解析器 93 ServletFileUpload upload = new ServletFileUpload(factory); 94 //解決上傳文件名的中文亂碼 95 upload.setHeaderEncoding("UTF-8"); 96 //三、判斷提交上來的數據是不是上傳表單的數據 97 /*if(!ServletFileUpload.isMultipartContent(request)){ 98 //按照傳統方式獲取數據 99 return; 100 }*/ 101 //四、使用ServletFileUpload解析器解析上傳數據,解析結果返回的是一個List<FileItem>集合,每個FileItem對應一個Form表單的輸入項 102 List<FileItem> list = upload.parseRequest(request); 103 for(FileItem item : list){ 104 //若是fileitem中封裝的是普通輸入項的數據 105 if(item.isFormField()){ 106 String name = item.getFieldName(); 107 //解決普通輸入項的數據的中文亂碼問題 108 String value = item.getString("UTF-8"); 109 //value = new String(value.getBytes("iso8859-1"),"UTF-8"); 110 System.out.println(name + "=" + value); 111 }else{//若是fileitem中封裝的是上傳文件 112 //獲得上傳的文件名稱, 113 String filename = item.getName(); 114 System.out.println(filename); 115 if(filename==null || filename.trim().equals("")){ 116 continue; 117 } 118 //注意:不一樣的瀏覽器提交的文件名是不同的,有些瀏覽器提交上來的文件名是帶有路徑的,如: c:\a\b\1.txt,而有些只是單純的文件名,如:1.txt 119 //處理獲取到的上傳文件的文件名的路徑部分,只保留文件名部分 120 filename = filename.substring(filename.lastIndexOf("\\")+1); 121 //獲取item中的上傳文件的輸入流 122 InputStream in = item.getInputStream(); 123 //建立一個文件輸出流 124 FileOutputStream out = new FileOutputStream(savePath + filename); 125 //建立一個緩衝區 126 byte buffer[] = new byte[1024]; 127 //判斷輸入流中的數據是否已經讀完的標識 128 int len = 0; 129 //循環將輸入流讀入到緩衝區當中,(len=in.read(buffer))>0就表示in裏面還有數據 130 while((len=in.read(buffer))>0){ 131 //使用FileOutputStream輸出流將緩衝區的數據寫入到指定的目錄(savePath + "\\" + filename)當中 132 out.write(buffer, 0, len); 133 } 134 //關閉輸入流 135 in.close(); 136 //關閉輸出流 137 out.close(); 138 //刪除處理文件上傳時生成的臨時文件 139 item.delete(); 140 message = "文件上傳成功!"; 141 } 142 } 143 }catch (Exception e) { 144 message= "文件上傳失敗!"; 145 e.printStackTrace(); 146 147 } 148 149 150 /*request.setAttribute("message",message); 151 request.getRequestDispatcher("properties/xnUploadFile/message.jsp").forward(request, response);*/ 152 } 153 154 public void doPost(HttpServletRequest request, HttpServletResponse response) 155 throws ServletException, IOException { 156 157 doGet(request, response); 158 } 159 }
servelet請求 web.xml中插入XnUploadFileController
<servlet-mapping>
<servlet-name>XnUploadFileController</servlet-name>
<url-pattern>/servlet/XnUploadFileController</url-pattern>
</servlet-mapping>
將文件存儲到某一目錄下:
//文件名
String savePath = this.getServletContext().getRealPath("/zjtjb/");
//String savePath ="D:/wuye/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/properties/upload/";
File file = new File(savePath);
//判斷上傳文件的保存目錄是否存在
if (!file.exists() && !file.isDirectory()) {
System.out.println(savePath+"目錄不存在,須要建立");
//建立目錄
file.mkdir();
}
//消息提示
String message = "";
存儲到某一目錄:
System.out.println(filename);
if(filename==null || filename.trim().equals("")){
continue;
}
//注意:不一樣的瀏覽器提交的文件名是不同的,有些瀏覽器提交上來的文件名是帶有路徑的,如: c:\a\b\1.txt,而有些只是單純的文件名,如:1.txt
//處理獲取到的上傳文件的文件名的路徑部分,只保留文件名部分
filename = filename.substring(filename.lastIndexOf("\\")+1);
//獲取item中的上傳文件的輸入流
InputStream in = item.getInputStream();
//建立一個文件輸出流
if (filename.contains("zjtjb")) {
//加上\ 才能生成目錄
savePath=savePath+"\\";
FileOutputStream out = new FileOutputStream(savePath+ filename);
//建立一個緩衝區
byte buffer[] = new byte[1024];
//判斷輸入流中的數據是否已經讀完的標識
int len = 0;
//循環將輸入流讀入到緩衝區當中,(len=in.read(buffer))>0就表示in裏面還有數據
while((len=in.read(buffer))>0){
//使用FileOutputStream輸出流將緩衝區的數據寫入到指定的目錄(savePath + "\\" + filename)當中
out.write(buffer, 0, len);
}
//關閉輸入流
in.close();
//關閉輸出流
out.close();
//刪除處理文件上傳時生成的臨時文件
item.delete();
message = "文件上傳成功!";
}
}
}
}catch (Exception e) {
message= "文件上傳失敗!";
e.printStackTrace();
}