您的位置:首页 > 编程语言 > Java开发

struts2上传文件的时候,action里面获取上传文件的文件名和类型的原理是什么?

2017-05-09 16:56 507 查看
阅文地址:http://blog.csdn.net/mmoooodd/article/details/49756593

网上看到比较细的解答,记录一下。http://www.iteye.com/problems/89011 正文:

jsp中

        <s:file name="upload" label="上传的文件" />

 action中,声明代码:

        private File upload;  

        private String uploadContentType; // 文件的内容类型  

        private String uploadFileName; // 上传文件名  

这里有个疑问, 文件名和文件类型是如何获取的?

约定,在struts2内部的的FileUploadInterceptor完成的

String[] fileName = multiWrapper.getFileNames(inputName);//得到请求的所有文件名

                if (isNonEmpty(fileName)) {

                    // get a File object for the uploaded File

                    File[] files = multiWrapper.getFiles(inputName);

                    if (files != null && files.length > 0) {

                        List<File> acceptedFiles = new ArrayList<File>(files.length);

                        List<String> acceptedContentTypes = new ArrayList<String>(files.length);

                        List<String> acceptedFileNames = new ArrayList<String>(files.length);

                        String contentTypeName = inputName + "ContentType";//默认就是input名称+ContentType

                        String fileNameName = inputName + "FileName";//默认就是input名称+FileName

                        for (int index = 0; index < files.length; index++) {

                            if (acceptFile(action, files[index], fileName[index], contentType[index], inputName, validation, ac.getLocale())) {

                                acceptedFiles.add(files[index]);

                                acceptedContentTypes.add(contentType[index]);

                                acceptedFileNames.add(fileName[index]);

                            }

                        }

                        if (!acceptedFiles.isEmpty()) {

                            Map<String, Object> params = ac.getParameters();//添加到parameters中 这样就可以通过OGNL注入到action了

                            params.put(inputName, acceptedFiles.toArray(new File[acceptedFiles.size()]));

                            params.put(contentTypeName, acceptedContentTypes.toArray(new String[acceptedContentTypes.size()]));

                            params.put(fileNameName, acceptedFileNames.toArray(new String[acceptedFileNames.size()]));

                        }

                    }

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: