1.android前端发送服务器请求
在spring-mvc.xml 将过滤屏蔽(如果不屏蔽 ,文件流为空)
<!-- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8"> <property name="maxUploadSize"> <value>2000000000</value>
</property> <property name="maxInMemorySize"> <value>2000000000</value> </property>
</bean> -->
2.在spring-mvc.xml 中加入请求url:<value>fileUploadController.do?uploads</value>
<!-- 拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="org.jeecgframework.core.interceptors.EncodingInterceptor" />
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="org.jeecgframework.core.interceptors.AuthInterceptor">
<property name="excludeUrls">
<list>
<value>loginController.do?goPwdInit</value>
<value>loginController.do?pwdInit</value>
<value>loginController.do?login</value>
<value>loginController.do?checkuser</value>
<value>systemController.do?saveFiles</value>
<value>systemController.do?saveFilesBeads</value>
<value>systemController.do?saveFilesCustomer</value>
<value>systemController.do?saveNews</value>
<value>iconController.do?saveIcon</value>
<value>userController.do?savesign</value>
<value>xiNaiInterfaceController.do?interface</value>
<value>fileUploadController.do?uploads</value>
<value>jpPersonController.do?importExcel</value> <!-- for:[119]excel导入风格统一 -->
</list>
</property>
</bean>
</mvc:interceptor>
</mvc:interceptors>
3.服务器请求 获取存储目录
linux服务器无法再创建目录,windows可以多加入tomcat下
http://192.168.0.112:8080/properties/fileUploadController.do?uploads
/***
* 文件上传例子 resource code encoding is utf-8
* <br>主要为了android客户端实现功能
*
*/
@Controller
@RequestMapping("/fileUploadController")
public class FileUploadController extends ActionSupport { @RequestMapping(params = "uploads")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter(); // 创建文件项目工厂对象
DiskFileItemFactory factory = new DiskFileItemFactory(); // 设置文件上传路径
//String upload="D:/sinia/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/properties/upload/"; String upload = request.getRealPath("/");
// 获取系统默认的临时文件保存路径,该路径为Tomcat根目录下的temp文件夹
String temp = System.getProperty("java.io.tmpdir");
// 设置缓冲区大小为 5M
factory.setSizeThreshold(1024 * 1024 * 5);
// 设置临时文件夹为temp
factory.setRepository(new File(temp));
// 用工厂实例化上传组件,ServletFileUpload 用来解析文件上传请求
ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
JSONObject ob = new JSONObject();
// 解析结果放在List中
try
{
List<FileItem> list = servletFileUpload.parseRequest(request); for (FileItem item : list)
{
String name = item.getFieldName();
InputStream is = item.getInputStream(); if (name.contains("content"))
{
System.out.println(inputStream2String(is));
}
else if(name.contains("file"))
{
try
{
inputStream2File(is, upload + "/" + item.getName()); //ob.put("path", upload + "\\" + item.getName());
ob.put("path", upload +item.getName());
out.write(ob.toString());
} catch (Exception e)
{
e.printStackTrace();
}
}
}
//out.write("success");
} catch (FileUploadException e)
{
out.write("failure");
} out.flush();
out.close();
}
// 流转化成字符串
public static String inputStream2String(InputStream is) throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i = -1;
while ((i = is.read()) != -1)
{
baos.write(i);
}
return baos.toString();
}
// 流转化成文件
public static void inputStream2File(InputStream is, String savePath)
throws Exception
{
System.out.println("文件保存路径为:" + savePath);
File file = new File(savePath);
InputStream inputSteam = is;
BufferedInputStream fis = new BufferedInputStream(inputSteam);
FileOutputStream fos = new FileOutputStream(file);
int f;
while ((f = fis.read()) != -1)
{
fos.write(f);
}
fos.flush();
fos.close();
fis.close();
inputSteam.close();
}
文件存储目录
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
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/servlet/XnUploadFileController" enctype="multipart/form-data" method="post">
上传文件:<input type="file" name="file"><br/>
<input type="submit" value="提交">
</form>
</body>
</html>
XnUploadFileController.java
package jeecg.properties; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import jeecg.system.pojo.base.TSDocument;
import jeecg.system.service.SystemService; import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.model.common.UploadFile;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.DataUtils;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.MyClassLoader;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView; import com.jspsmart.upload.SmartUpload; @Controller
@RequestMapping("/xnUploadFileController")
public class XnUploadFileController extends HttpServlet{
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(XnUploadFileController.class); @Autowired
private SystemService systemService;
private String message; public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
}
@RequestMapping(params = "upload")
public ModelAndView upload(HttpServletRequest request) {
return new ModelAndView("properties/xnUploadFile/uploadfile");
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { //得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全 /**
*
* 在server 目录里创建upload文件夹
*
* .metadata\.plugins\org.eclipse.wst.server.core
*
*/ String savePath = this.getServletContext().getRealPath("/");
//String savePath ="D:/sinia/.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 = "";
try{
//使用Apache文件上传组件处理文件上传步骤:
//1、创建一个DiskFileItemFactory工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//2、创建一个文件上传解析器
ServletFileUpload upload = new ServletFileUpload(factory);
//解决上传文件名的中文乱码
upload.setHeaderEncoding("UTF-8");
//3、判断提交上来的数据是否是上传表单的数据
/*if(!ServletFileUpload.isMultipartContent(request)){
//按照传统方式获取数据
return;
}*/
//4、使用ServletFileUpload解析器解析上传数据,解析结果返回的是一个List<FileItem>集合,每一个FileItem对应一个Form表单的输入项
List<FileItem> list = upload.parseRequest(request);
for(FileItem item : list){
//如果fileitem中封装的是普通输入项的数据
if(item.isFormField()){
String name = item.getFieldName();
//解决普通输入项的数据的中文乱码问题
String value = item.getString("UTF-8");
//value = new String(value.getBytes("iso8859-1"),"UTF-8");
System.out.println(name + "=" + value);
}else{//如果fileitem中封装的是上传文件
//得到上传的文件名称,
String filename = item.getName();
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();
//创建一个文件输出流
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(); } /*request.setAttribute("message",message);
request.getRequestDispatcher("properties/xnUploadFile/message.jsp").forward(request, response);*/
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { doGet(request, response);
}
}
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();
}