浏览代码

上传下载优化

huangbo 9 年之前
父节点
当前提交
8de98a9f6e

+ 82 - 245
display-server/src/com/ai/server/bean/UploadDownloadBean.java

@ -1,26 +1,18 @@
1 1
package com.ai.server.bean;
2 2

3
import java.io.BufferedInputStream;
4
import java.io.BufferedOutputStream;
5 3
import java.io.File;
6 4
import java.io.FileInputStream;
7 5
import java.io.FileOutputStream;
8 6
import java.io.InputStream;
9 7
import java.io.OutputStream;
10
import java.text.SimpleDateFormat;
11
import java.util.Date;
12
import java.util.Iterator;
13 8
import java.util.List;
14 9

15 10
import javax.servlet.http.HttpServletRequest;
16 11
import javax.servlet.http.HttpServletResponse;
17 12

18 13
import org.apache.commons.fileupload.FileItem;
19
import org.apache.commons.fileupload.FileItemFactory;
20 14
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
21 15
import org.apache.commons.fileupload.servlet.ServletFileUpload;
22
import org.apache.commons.fileupload.util.Streams;
23
import org.apache.commons.lang.StringUtils;
24 16

25 17
import com.ai.server.core.bean.DisplayBean;
26 18
import com.ai.server.util.ApplicationPath;
@ -31,270 +23,115 @@ import com.ailk.mobile.util.FileUtil;
31 23
import com.ailk.mobile.util.MobileUtility;
32 24

33 25
/**
34
 * 
35
 * @author Lu
36
 *
26
 * @author huangbo
27
 * @date 2016-1-9 下午2:32:20 
28
 * @desc 上传下载使用范例
37 29
 */
38 30
public class UploadDownloadBean extends DisplayBean {
39 31
    
40
    /**
41
    * @Fields hasTimeRandom : 上传图片的路径中,是否包含时间串儿,例如:201511022351123_1234
42
    * 如果为true,则可以保证每次上传的图片不重名,可以保留原文件的名称不变,下载时候可获取原文件的名称。
43
    * 
44
    */
45
    private final boolean hasTimeRandom = false;
46
    
47
	/************************************************************************************
48
	 * 文件上传;
49
	 * 如果在参数param中包含USER_NAME键值对,那么文件将保存到USER_NAME对应的目录下;否则保存在TEMP目录下
50
	 * 
51
	 * @param param
52
	 * @return
53
	 * @throws Exception
32
	/**
33
	 * 文件上传
54 34
	 */
55
	/*public IData upload(IData param) throws Exception{
56
	    IData result = new DataMap();
35
	@SuppressWarnings("unchecked")
36
	public IData upload(IData param) throws Exception{
37
		/*1.判断请求和参数是否合法*/
38
		String filePath = param.getString("FILE_PATH", ""); //通过自定义参数决定文件存储规则
39
		if(filePath.equals("")){
40
			MobileUtility.error("请设置文件存储路径!");
41
		}
42
		/**固定文件名用于该场景测试*/
43
		String fileName = FileUtil.connectFilePath(filePath, "my.png");
44
		
57 45
		HttpServletRequest request = ServletManager.getRequest();
58 46
		if (!ServletFileUpload.isMultipartContent(request)) {
59
			MobileUtility.error("获取的上传文件并非以文件流格式传送,请核查!");
47
			MobileUtility.error("没有检测到文件,请重新提交!");
60 48
		}
61 49
		
62
		//没有则存储在临时目录
63
		String uploadPath = param.getString("UPLOAD_PATH","temp");
64
		//目录转换
65
		uploadPath = uploadPath.replace("\\", File.separator).replace("/", File.separator);
66
		//获取文件需要上传到的路径
67
		String savePath = FileUtil.connectFilePath(ApplicationPath.getFilePath(request), "upload", uploadPath);
68
		//result.put("SAVE_PATH", savePath);
69
		
70
		File file = new File(savePath);
50
		File file = new File(filePath);
71 51
		if(! file.exists() && ! file.mkdirs()){
72
			MobileUtility.error("生成上传临时文件夹失败,无法进行上传操作!");
52
			MobileUtility.error("创建上传文件夹失败!");
73 53
		}
74 54
		
75
		String fileName = param.getString("FILE_NAME",String.valueOf(System.currentTimeMillis()));
76
		//result.put("FILE_NAME", fileName);
77
		
78
		//获得磁盘文件条目工厂
79
		DiskFileItemFactory factory = new DiskFileItemFactory();
80
        //设置暂时存放的存储室,这个存储室可以和最终存储文件的目录不同
81
        factory.setRepository(file);
82
        //设置缓存的大小,当上传文件的容量超过该缓存时,将产生临时文件并存储于临时目录中.
83
        factory.setSizeThreshold(5*1024*1024);
84
        //文件上传处理
55
		/*2.处理上传文件的业务逻辑*/
56
		IData result = new DataMap();
57
		DiskFileItemFactory factory = new DiskFileItemFactory(); //获得磁盘文件条目工厂
58
        //factory.setSizeThreshold(5*1024*1024); //设置缓存的大小。上传文件超过缓存时,将存储在临时目录中。
59
        //factory.setRepository(file); //设置临时存储
85 60
        ServletFileUpload upload = new ServletFileUpload(factory);
86
        
61
        OutputStream out = null;
62
        InputStream in = null;
63
        System.out.println(ApplicationPath.getFilePath(request));
87 64
		try{
88
        	List<?> fileList = upload.parseRequest(request);
65
			/*多个上传文件*/
66
            List<FileItem> fileList = upload.parseRequest(request);
89 67
            for(int i = 0; i < fileList.size(); i++){
90
            	FileItem item = (FileItem)fileList.get(i);
91
                //获取表单的属性名
92
                String name = item.getFieldName();
93
                 
94
            	//如果获取的 表单信息是普通的文本信息
95
                if(item.isFormField()){
96
                 	//获取用户具体输入的字符串,因为表单提交过来的是字符串类型的
97
                 	String value = item.getString();
98
                    request.setAttribute(name, value);
99
                    //获取用户保存目录
68
            	FileItem item = fileList.get(i);
69
                String name = item.getFieldName();//获取表单的属性名
70
                
71
                /*处理表单数据*/
72
                if (item.isFormField()) {
73
                    request.setAttribute(name, item.getString());
100 74
                }else{
101
                	//获取路径名
102
	             	String value = item.getName();
103
	                int start = value.lastIndexOf("\\");
104
	                String filename = value.substring(start + 1);
105
	                //保存文件名
106
	                request.setAttribute(name, filename);
107
	                
108
	                //检查保存目录
109
	                File saveDir = new File(savePath);
110
	         		if(! saveDir.exists() && ! saveDir.mkdirs()){
111
	         			MobileUtility.error("生成上传保存文件夹失败,无法进行上传操作!");
112
	         		}
113
	         		//设置保存文件
114
	                File saveFile = new File(savePath, filename);
115
	                //写到磁盘上
116
	                OutputStream out = new FileOutputStream(saveFile);
117
	                InputStream in = item.getInputStream();
118
	                
75
					String value = item.getName();
76
					request.setAttribute(name, value); // 保存文件名
77
	         		/*保存文件*/
78
	                File uploadFile = new File(fileName);
79
	                out = new FileOutputStream(uploadFile);
80
	                in = item.getInputStream();
119 81
	                int length = 0;
120 82
	                byte[] buf = new byte[1024];
121
	                //写出到文件中
122 83
	                while((length = in.read(buf) ) != -1) {
123
	                    //在BUF数组中取出数据写到(输出流)磁盘上
124 84
	                    out.write(buf, 0, length);
125 85
	                }
126
	                out.flush();
127
	                in.close();
128
	                out.close();
129
	                log.debug("获取上传文件的总共的容量:" + item.getSize());
130
	                result.put("size", item.getSize());
131
               }
132
           }
86
	                log.debug("上传文件大小为:" + item.getSize());
87
                }
88
        	}
89
            result.put("FILE_NMAE", fileName);
133 90
       }catch (Exception e) {
134 91
    	   MobileUtility.error("上传失败", e);
92
       }finally{
93
    	   if(in!=null)
94
    		   in.close();
95
    	   if(out!=null)
96
    		   out.close();
135 97
       }
136 98
       return result;
137
	}*/
138
	/************************************************************************************
139
	 * 文件下载;
140
	 * 
141
	 * @param param
142
	 * @return
143
	 * @throws Exception
144
	 */
145
	/*public IData download(IData param) throws Exception{
146
		HttpServletRequest request = ServletManager.getRequest();
147
		HttpServletResponse response = ServletManager.getResponse();
148
		//获取文件需要上传到的路径
149
		String fileName = request.getParameter("FILE_PATH");
150
		String mineType = request.getParameter("MINE_TYPE");
151
		log.debug("MINE类型为:[" + mineType + "]");
152
//		log.debug(request.getParameter("USER_NAME"));
153
//		log.debug(request.getParameter("SESSION_ID"));
154
		//获取文件地址
155
		String filePath = ApplicationPath.getFilePath(request) + "upload" + File.separator + fileName;
156
		File file = new File(filePath);
157
		if(! file.isFile())
158
			throw new RuntimeException("上传的文件不存在,请检查文件路径!");
159

160
		response.reset();
161
		response.setContentType(mineType);
162
		InputStream in = new FileInputStream(file);
163
        
164
        int length = 0;
165
        byte[] buf = new byte[1024];
166
        //写出到文件中
167
        OutputStream out = response.getOutputStream();
168
        while((length = in.read(buf) ) != -1) {
169
            //在BUF数组中取出数据写到(输出流)磁盘上
170
        	out.write(buf, 0, length);
171
        }
172
        out.flush();
173
        in.close();
174
        out.close();
175
        response.flushBuffer();
176
		
177
		return null;
178
	}*/
99
	}
179 100
	
180
	public IData upload(IData param) throws Exception{
181
	    IData returnMap = new DataMap();  // 返回的对象
182
        HttpServletRequest request = ServletManager.getRequest();
183
        HttpServletResponse response = ServletManager.getResponse();
184
        response.setContentType("text/html;charset=UTF-8");
185
        response.setHeader("Cache-Control", "no-cache");
186
        if (!ServletFileUpload.isMultipartContent(request)) {
187
            MobileUtility.error("获取的上传文件并非以文件流格式传送,请核查!");
188
        }
189
        
190
        log.debug("【上传资源开始。。。】");
191
        Date date = new Date();// 获取当前时间
192
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
193
        String dateStr = formatter.format(date);
194
        int random = (int)(Math.random()*10000);
195
        String dateStr_random = dateStr+"_"+random;  //时间字符串+随机数 最后一级别的文件夹
196
        String path = null; // 存放数据库用 相对路径 path = typePath + dateStr_random + fileName
197
        String rootDir = ApplicationPath.getFilePath(request).replace("//", File.separator).replace("\\", File.separator) + "upload"; // eg:F:\eclipseWorkspace3\android-share\display-server\web
198
        String typePath = null;
199
        String filePath = null;  // 上传服务器用 绝对路径 filePath = rootDir + typePath + dateStr_random + fileName
200
        String fileName = null;
201
        BufferedInputStream in = null;
202
        BufferedOutputStream outStream = null;
203
        try {
204
            // 获得磁盘文件条目工厂
205
            FileItemFactory factory = new DiskFileItemFactory();
206
            // 高水平的API文件上传处理
207
            ServletFileUpload upload = new ServletFileUpload(factory);
208
            upload.setHeaderEncoding("UTF-8");
209
            // 获取多个上传文件
210
            List<?> fileList = upload.parseRequest(request);
211
            // 遍历上传文件写入磁盘
212
            Iterator<?> it = fileList.iterator();
213
            
214
            while (it.hasNext()) {
215
                FileItem item = (FileItem) it.next();
216
                if (item == null) {
217
                    continue;
218
                }
219
                //获取表单的属性名字
220
                String name = item.getFieldName();
221
                //如果获取的表单信息,是普通的文本信息
222
                if (item.isFormField()) {
223
                    //获取用户具体输入的字符串,因为表单提交过来的是字符串类型的
224
                    String value = item.getString();
225
                    if ("data".equals(name)) {
226
                        IData postData = new DataMap(value);
227
                        typePath = postData.getString("UPLOAD_PATH", "temp");
228
                        fileName = postData.getString("FILE_NAME");
229
                    }
230
                    request.setAttribute(name, value);
231
                    continue;
232
                }
233
                
234
                // 获取路径名
235
                String value = item.getName();
236
                if (value != null) {
237
                    // 索引到最后一个反斜杠
238
                    int start = value.lastIndexOf("\\");
239
                    // 截取 上传文件的 字符串名字,加1是 去掉反斜杠,
240
                    String originalFileName = value.substring(start + 1);   // 文件名称
241
                    if (StringUtils.isEmpty(fileName)) {
242
                        fileName = originalFileName;
243
                    } 
244
                    
245
                    String mulu = null;
246
                    if (hasTimeRandom) {
247
                        path = FileUtil.connectFilePath(typePath, dateStr_random, fileName);
248
                        mulu = FileUtil.connectFilePath(rootDir, typePath, dateStr_random);
249
                    }
250
                    else {
251
                        path = FileUtil.connectFilePath(typePath, fileName);
252
                        mulu = FileUtil.connectFilePath(rootDir, typePath);
253
                    }
254
                    filePath = FileUtil.connectFilePath(rootDir, path);
255
                    File file = new File(mulu);
256
                    if (!file.isDirectory()) {
257
                        log.debug("目录不存在,自动生成目录:" + mulu);
258
                        file.mkdirs();
259
                    }
260
                    in = new BufferedInputStream(item.getInputStream());// 获得文件输入流
261
                    outStream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));// 获得文件输出流
262
                    long filelenth = Streams.copy(in, outStream, true);// 开始把文件写到你指定的上传文件夹
263
                    
264
                    returnMap.put("size", filelenth);
265
                    returnMap.put("lujing", path);
266
                    returnMap.put("fileName", fileName);
267
                    
268
                }
269
            }
270
            log.debug("【上传结束:】" + returnMap.toString());
271
        } catch (Exception e) {
272
            // TODO Auto-generated catch block
273
            e.printStackTrace();
274
        }
275
        finally {
276
            if (in != null) {
277
                try {
278
                    in.close();
279
                }
280
                catch (Exception e) {
281
                    throw new RuntimeException(e);
282
                }
283

284
            }
285
            if (outStream != null) {
286
                try {
287
                    outStream.close();
288
                }
289
                catch (Exception e) {
290
                    throw new RuntimeException(e);
291
                }
101
	/*public IData download(IData param) throws Exception{
102
	HttpServletRequest request = ServletManager.getRequest();
103
	HttpServletResponse response = ServletManager.getResponse();
104
	//获取文件需要上传到的路径
105
	String fileName = request.getParameter("FILE_PATH");
106
	String mineType = request.getParameter("MINE_TYPE");
107
	log.debug("MINE类型为:[" + mineType + "]");
108
//	log.debug(request.getParameter("USER_NAME"));
109
//	log.debug(request.getParameter("SESSION_ID"));
110
	//获取文件地址
111
	String filePath = ApplicationPath.getFilePath(request) + "upload" + File.separator + fileName;
112
	File file = new File(filePath);
113
	if(! file.isFile())
114
		throw new RuntimeException("上传的文件不存在,请检查文件路径!");
292 115

293
            }
294
        }
295
       
296
        return returnMap;
116
	response.reset();
117
	response.setContentType(mineType);
118
	InputStream in = new FileInputStream(file);
119
    
120
    int length = 0;
121
    byte[] buf = new byte[1024];
122
    //写出到文件中
123
    OutputStream out = response.getOutputStream();
124
    while((length = in.read(buf) ) != -1) {
125
        //在BUF数组中取出数据写到(输出流)磁盘上
126
    	out.write(buf, 0, length);
297 127
    }
128
    out.flush();
129
    in.close();
130
    out.close();
131
    response.flushBuffer();
132
	
133
	return null;
134
}*/
298 135
	
299 136
	public InputStream download(IData param) throws Exception{
300 137
        HttpServletRequest request = ServletManager.getRequest();

+ 34 - 15
display-server/web/biz/js/plugin/uploaddownload.js

@ -1,33 +1,52 @@
1 1
require(["domReady!","wadeMobile", "util"], function(doc,WadeMobile) {
2
	var iscroll = new iScroll("content");
3
	var picDir = "picture";
4
	
5
	/*选择图片*/
6
	$("#getPicture").tap(function() {
7
		WadeMobile.getPicture(function(filePath){
8
			$("#uploadFilePath").html(filePath);
9
		});
10
	});
11
	
2 12
	//上传
3 13
	$("#upload").tap(function() {
14
		var uploadFile = $("#uploadFilePath").html();
15
		if(!uploadFile){
16
			alert("请先选择上传文件!");
17
			return;
18
		}
4 19
		/*单文件上传*/
5
		WadeMobile.getPicture(function(filePath){
6
			var params = Wade.DataMap();
7
			params.put("UPLOAD_PATH","photo"); // 图片上传的制定相对路径,如果没有设置,默认值temp
8
			params.put("FILE_NAME","my.png");   // 图片默认的名字,如果没有设置,取原图片的名字
9
			//服务端SESSION_ID不能为空,服务端配置verify="false"并不校验
10
			params.put("SESSION_ID",new Date().getTime());
11
			WadeMobile.uploadWithServlet(filePath, "UploadDownloadBean.upload", params.toString(), function(result){
12
				var data = new Wade.DataMap(result);
13
				alert(result);
14
				alert("上传文件的大小:" + data.get("size") + "字节,文件路径:" + data.get("lujing"));
15
				$("#fileUpload").html(data.get("lujing"));
16
			});
20
		var params = Wade.DataMap();
21
		params.put("FILE_PATH",picDir);
22
		//服务端SESSION_ID不能为空,服务端配置verify="false"并不校验
23
		params.put("SESSION_ID",new Date().getTime());
24
		WadeMobile.uploadWithServlet(uploadFile, "UploadDownloadBean.upload", params.toString(), function(result){
25
			alert(result);
26
			var data = new Wade.DataMap(result);
27
			alert(data);
28
			$("#fileUpload").html(data.get("FILE_NMAE"));
17 29
		});
18 30
		/*多文件上传*/
31
		//有待补充
19 32
	});
20 33
	
21 34
	//下载
22 35
	$("#download").tap(function() {
23 36
		//文件保存路径
24
		var savePath = "/my123.png";
25
		
37
		var savePath = picDir+"/my.png"; //支持绝对路径和相对路径
26 38
		var params = new Wade.DataMap();
27
		params.put("FILE_PATH", "photo/my.png");//下载文件的相对路径
39
		params.put("FILE_PATH", picDir);//下载文件的相对路径
28 40
		//服务端SESSION_ID不能为空,服务端配置verify="false"并不校验
29 41
		params.put("SESSION_ID",new Date().getTime());
30 42
		WadeMobile.downloadWithServlet(savePath, "UploadDownloadBean.download", params.toString(), function(result){
43
			$("#downloadFilePath").html(savePath);
44
			
45
			/*var width = $("#downloadPicture").width();
46
			var height = $("#downloadPicture").height();
47
			$("#downloadPicture").removeClass("e_imagePlaceHolder");
48
			$("#downloadPicture").html("<img height='" + height + "' width='" + width + "' src='" + path + "'/>");
49
			iscroll.refresh();*/
31 50
			alert(result);
32 51
		});
33 52
	});