Bladeren bron

@laijj@调试文件上传

赖骏劼 2 jaren geleden
bovenliggende
commit
56a617a143

+ 129 - 96
ipu-show-server/src/main/java/com/ai/ipu/show/bean/UploadDownloadBean.java

@ -1,10 +1,6 @@
1 1
package com.ai.ipu.show.bean;
2 2
3
import java.io.File;
4
import java.io.FileInputStream;
5
import java.io.FileOutputStream;
6
import java.io.InputStream;
7
import java.io.OutputStream;
3
import java.io.*;
8 4
import java.util.List;
9 5
10 6
import javax.servlet.http.HttpServletRequest;
@ -25,102 +21,139 @@ import com.ai.ipu.basic.log.IpuLoggerFactory;
25 21
26 22
/**
27 23
 * @author huangbo
28
 * @date 2016-1-9 下午2:32:20 
24
 * @date 2016-1-9 下午2:32:20
29 25
 * @desc 上传下载使用范例
30 26
 */
31 27
public class UploadDownloadBean extends IpuAppBean {
32 28
33
	/**
34
	 * log在子类重新定义
35
	 */
36
	protected static final transient ILogger log = IpuLoggerFactory.getLogger(UploadDownloadBean.class);
37
    
38
	/**
39
	 * 文件上传
40
	 */
41
	public IData upload(IData param) throws Exception {
42
		/* 1.判断请求和参数是否合法 */
43
		String filePathStr = param.getString("FILE_PATH", ""); // 通过自定义参数决定文件存储规则
44
		String[] filePaths = filePathStr.split(",");
45
		if (filePaths.length == 0) {
46
			MobileUtility.error("请设置文件存储路径!");
47
		}
48
		/* 1.2.判断请求是否包含文件信息 */
49
		HttpServletRequest request = ServletManager.getRequest();
50
		if (!ServletFileUpload.isMultipartContent(request)) {
51
			MobileUtility.error("没有检测到文件,请重新提交!");
52
		}
29
    /**
30
     * log在子类重新定义
31
     */
32
    protected static final transient ILogger log = IpuLoggerFactory.getLogger(UploadDownloadBean.class);
53 33
54
		/* 2.处理上传文件的业务逻辑 */
55
		IData result = new DataMap();
56
		DiskFileItemFactory factory = new DiskFileItemFactory(); // 获得磁盘文件条目工厂
57
		// factory.setSizeThreshold(5*1024*1024); //设置缓存的大小。上传文件超过缓存时,将存储在临时目录中。
58
		// factory.setRepository(file); //设置临时存储
59
		ServletFileUpload upload = new ServletFileUpload(factory);
60
		OutputStream out = null;
61
		InputStream in = null;
62
		String filePath = null, savePath = ""; // 文件地址
63
		/* 多个上传文件 */
64
		List<FileItem> fileList = upload.parseRequest(request);
65
		// 多文件上传判断 还有些问题,未调通
66
		// if(fileList.size() != filePaths.length){
67
		// MobileUtility.error("提交的文件数量和保存的文件列表数量不一致,请检查参数!");
68
		// }
69
		for (int i = 0; i < fileList.size(); i++) {
70
			FileItem item = fileList.get(i);
71
			String name = item.getFieldName();// 获取表单的属性名
34
    /**
35
     * 文件上传
36
     */
37
    public IData upload(IData param) throws Exception {
38
        log.info("调用upload功能");
39
        IData result = new DataMap();//返回参数
40
        /* 1.判断请求和参数是否合法 */
41
        String filePathStr = param.getString("FILE_PATH", ""); // 通过自定义参数决定文件存储规则
42
        String[] filePaths = filePathStr.split(",");
43
        if (filePaths.length == 0) {
44
            MobileUtility.error("请设置文件存储路径!");
45
        }
46
        log.info("调用upload功能,filePathStr:" + filePathStr);
47
        /* 1.2.判断请求是否包含文件信息 */
48
        HttpServletRequest request = ServletManager.getRequest();
49
        if (!ServletFileUpload.isMultipartContent(request)) {
50
            MobileUtility.error("没有检测到文件,请重新提交!");
51
        }
52
        /* 2.处理上传文件的业务逻辑 */
53
        String filePath = null;  // 文件地址
54
        StringBuilder savePath = new StringBuilder();
55
        DiskFileItemFactory factory = new DiskFileItemFactory(); // 获得磁盘文件条目工厂
56
        ServletFileUpload upload = new ServletFileUpload(factory);
57
        /* 多个上传文件 */
58
        List<FileItem> fileList = upload.parseRequest(request);
59
        // 多文件上传判断 还有些问题,未调通
60
        // if(fileList.size() != filePaths.length){
61
        // MobileUtility.error("提交的文件数量和保存的文件列表数量不一致,请检查参数!");
62
        // }
63
        for (int i = 0; i < fileList.size(); i++) {
64
            FileItem item = fileList.get(i);
65
            // 获取表单的属性名
66
            String name = item.getFieldName();
67
            log.info("调用upload功能,fileList[" + i + "],name:" + name);
68
            /* 处理表单数据 */
69
            if (item.isFormField()) {
70
                request.setAttribute(name, item.getString());
71
            } else {
72
                String value = item.getName();
73
                // 保存文件名
74
                request.setAttribute(name, value);
75
                // 文件在server上保存地址
76
                filePath = ApplicationPath.getFilePath(request) + filePaths[i];
77
                log.debug("调用upload功能,filePath:" + filePath);
78
                File dir = new File(filePath).getParentFile();
79
                if (!dir.exists() && !dir.mkdirs()) {
80
                    MobileUtility.error("创建上传文件夹失败!");
81
                }
82
                savePath.append(filePath).append(",");
83
                log.debug("调用upload功能,拼接savePath:" + savePath);
84
                /* 保存文件 */
85
                File uploadFile = new File(filePath);
86
                saveFile(item, uploadFile);
87
                log.debug("调用upload功能,保存图片成功");
88
//				OutputStream out = null;
89
//				InputStream in = null;
90
//				try {
91
//					out = new FileOutputStream(uploadFile);
92
//					in = item.getInputStream();
93
//					int length = 0;
94
//					byte[] buf = new byte[1024];
95
//					while ((length = in.read(buf)) != -1) {
96
//						out.write(buf, 0, length);
97
//					}
98
//					log.debug("上传文件大小为:" + item.getSize());
99
//				} catch (Exception e) {
100
//					MobileUtility.error("上传文件失败!", e);
101
//				} finally {
102
//					if (in != null) {
103
//						in.close();
104
//					}
105
//					if (out != null) {
106
//						out.close();
107
//					}
108
//				}
109
            }
110
        }
111
        result.put("FILE_PATH", savePath.substring(0, savePath.length() - 1));
112
        result.put("MEESSAG", "上传文件成功:" + filePath);
113
        return result;
114
    }
72 115
73
			/* 处理表单数据 */
74
			if (item.isFormField()) {
75
				request.setAttribute(name, item.getString());
76
			} else {
77
				String value = item.getName();
78
				request.setAttribute(name, value); // 保存文件名
79
				// 文件在server上保存地址
80
				filePath = ApplicationPath.getFilePath(request) + filePaths[i];
81
				File dir = new File(filePath).getParentFile();
82
				if (!dir.exists() && !dir.mkdirs()) {
83
					MobileUtility.error("创建上传文件夹失败!");
84
				}
85
				savePath += filePath + ",";
86
				/* 保存文件 */
87
				File uploadFile = new File(filePath);
88
				try {
89
					out = new FileOutputStream(uploadFile);
90
					in = item.getInputStream();
91
					int length = 0;
92
					byte[] buf = new byte[1024];
93
					while ((length = in.read(buf)) != -1) {
94
						out.write(buf, 0, length);
95
					}
96
					log.debug("上传文件大小为:" + item.getSize());
97
				} catch (Exception e) {
98
					MobileUtility.error("上传文件失败!", e);
99
				} finally {
100
					if (in != null) {
101
						in.close();
102
					}
103
					if (out != null) {
104
						out.close();
105
					}
106
				}
107
			}
108
		}
109
		result.put("FILE_PATH", savePath.substring(0, savePath.length() - 1));
110
		result.put("MEESSAG", "上传文件成功:" + filePath);
111
		return result;
112
	}
113
	
114
	public InputStream download(IData param) throws Exception {
115
		String filePath = param.getString("FILE_PATH");
116
		HttpServletRequest request = ServletManager.getRequest();
117
		filePath = ApplicationPath.getFilePath(request) + filePath;
118
		
119
		File file = new File(filePath);
120
		if (!file.isFile()) {
121
			MobileUtility.error("没有指定的文件可供下载,请先上传文件!");
122
		}
116
    /**
117
     * 保存文件方法
118
     *
119
     * @param item
120
     * @param uploadFile
121
     * @throws IOException
122
     */
123
    private void saveFile(FileItem item, File uploadFile) throws IOException {
124
        OutputStream out = null;
125
        InputStream in = null;
126
        try {
127
            out = new FileOutputStream(uploadFile);
128
            in = item.getInputStream();
129
            int length = 0;
130
            byte[] buf = new byte[1024];
131
            while ((length = in.read(buf)) != -1) {
132
                out.write(buf, 0, length);
133
            }
134
            log.debug("上传文件大小为:" + item.getSize());
135
        } catch (Exception e) {
136
            MobileUtility.error("上传文件失败!", e);
137
        } finally {
138
            if (in != null) {
139
                in.close();
140
            }
141
            if (out != null) {
142
                out.close();
143
            }
144
        }
145
    }
123 146
124
		return new FileInputStream(file);
125
	}
147
    public InputStream download(IData param) throws Exception {
148
        String filePath = param.getString("FILE_PATH");
149
        HttpServletRequest request = ServletManager.getRequest();
150
        filePath = ApplicationPath.getFilePath(request) + filePath;
151
152
        File file = new File(filePath);
153
        if (!file.isFile()) {
154
            MobileUtility.error("没有指定的文件可供下载,请先上传文件!");
155
        }
156
157
        return new FileInputStream(file);
158
    }
126 159
}

+ 0 - 1
ipu-show-server/src/main/java/com/ai/ipu/show/util/ApplicationPath.java

@ -22,7 +22,6 @@ public final class ApplicationPath {
22 22
			
23 23
			if(serverType.equals("T")){
24 24
				appFilePath = request.getSession().getServletContext().getRealPath("/");
25
				
26 25
			}else{
27 26
				appFilePath = request.getSession().getServletContext().getResource("/").getPath();
28 27
			}