1.android前端发送服务器请求

 在spring-mvc.xml 将过滤屏蔽(如果不屏蔽 ,文件流为空)

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.服务器请求 获取存储目录

linux服务器无法再创建目录,windows可以多加入tomcat下

http://192.168.0.112:8080/properties/fileUploadController.do?uploads

  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     }

文件存储目录 

D:/sinia/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/properties

后台加入上传功能:jsp上传文档:

jsp文档 加入上传功能

<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             //1、创建一个DiskFileItemFactory工厂
 91             DiskFileItemFactory factory = new DiskFileItemFactory();
 92             //2、创建一个文件上传解析器
 93             ServletFileUpload upload = new ServletFileUpload(factory);
 94             //解决上传文件名的中文乱码
 95             upload.setHeaderEncoding("UTF-8"); 
 96             //3、判断提交上来的数据是否是上传表单的数据
 97             /*if(!ServletFileUpload.isMultipartContent(request)){
 98                 //按照传统方式获取数据
 99                 return;
100             }*/
101             //4、使用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();

}