码迷,mamicode.com
首页 > 编程语言 > 详细

2015-6-2 文件的上传java

时间:2015-06-02 14:57:21      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

文件上传或者点击确定后

文件接收到请求和请求一块过来的参数

技术分享
 1 public class UplocadAo extends BaseAo implements ModelDriven<QuestionVo>{
 2     
 3     QuestionVo questionVo = new QuestionVo();    
 4     public void uploadFile(){        
 5         UploadFileBo ufb = new UploadFileBo();
 6         String resultstr = "{status:1,imgName:";
 7         try{
 8 //            UploadFileBo bo = (UploadFileBo)SpringFactory.getInstance().getBean("uploadFileBo");
 9             resultstr = ufb.doUploadFile(request, response,questionVo.getDomainCode(),questionVo.getQuestionBankId(),questionVo.getOperatorUserAccount());            
10             String xmlUrl =  Configer.getInstance().getProperty("save_xlsUrl");            
11             Logger.getLogger().debug("返回给前台的路径************************************************"+resultstr);
12             //resultstr = "{\"status\":1,\"xmlUrl\":\""+resultstr+"\"}";    
13             System.out.println(resultstr);
14         }catch(Exception ex){
15             resultstr = "{\"status\":0,\"xmlUrl\":}";
16             ex.printStackTrace();
17         }
18         
19         this.outString(resultstr, "text/html; charset=utf-8");
20         
21     }
View Code

上一篇中 返回的参数类型的json 所以这个Ao也要输出一个json格式的数据 resultstr  resultstr = "{\"status\":0,\"xmlUrl\":}"; \这个是反转意的意思 让字符串编程json

技术分享
 1     public String doUploadFile(HttpServletRequest request,HttpServletResponse response,String  domainCode,Long questionBankId,String operatorUserAccount ) {
 2         String resutlstr = "";
 3         QuestionBo qb = new QuestionBo();
 4         try {
 5             request.setCharacterEncoding("utf-8");
 6         } catch (UnsupportedEncodingException e1) {
 7             // TODO Auto-generated catch block
 8             e1.printStackTrace();
 9         }  
10         
11         
12         //System.out.println(request.getContentLength()); 文件的大小
13         //判断提交过来的表单是否为文件上传菜单  
14         boolean isMultipart= ServletFileUpload.isMultipartContent(request);  
15         if(isMultipart){  
16             //构造一个文件上传处理对象  
17             FileItemFactory factory = new DiskFileItemFactory();  
18             ServletFileUpload upload = new ServletFileUpload(factory);  
19   
20             Iterator items;  
21             try{  
22                 //解析表单中提交的所有文件内容  
23                 items = upload.parseRequest(request).iterator();  
24                 while(items.hasNext()){  
25                     FileItem item = (FileItem) items.next();  
26                     if(!item.isFormField()){  
27                         //取出上传文件的文件名称  
28                         String name = item.getName();   //photo:image/jpeg  excle:
29                         Logger.getLogger().debug("文件的名称*********************************"+name);
30                         long fileSize = item.getSize();
31                         //去除上传文件的类型
32                         String type = item.getContentType();
33                         //取得上传文件以后的存储路径  
34                         String fileName = name.substring(name.lastIndexOf(‘\\‘) + 1, name.length());  
35                         Logger.getLogger().debug("filename"+fileName);
36                         fileName = fileName.substring(fileName.lastIndexOf("."), fileName.length());
37                         fileName = Tools.getUUID()+fileName;                        
38                         //上传文件以后的存储路径 
39                         Logger.getLogger().debug("*****image/pjpeg   image/x-png*******************************########"+type);
40                         String saveDir = "";
41                         if("image/jpeg".equals(type) ||"image/pjpeg".equals(type)||"image/x-png".equals(type)|| 
42                                 "image/png".equals(type) || "image/bmp".equals(type) ){
43                             saveDir = Configer.getInstance().getProperty("save_imgUrl");    
44                         }else if("application/vnd.ms-excel".equals(type)){                            
45                             saveDir = Configer.getInstance().getProperty("save_xlsUrl");    
46                         }else if( fileSize > ( 1024*400)) {
47                             resutlstr= "largesize";
48                         }else{
49                             resutlstr= "patternerror";
50                         }   
51                         
52                         
53                         if(StringUtils.isNotBlank(saveDir)) {
54                               //这个创建文件夹会出错 
55                             if (!(new File(saveDir).isDirectory())){  
56                                 new File(saveDir).mkdir();  
57                                 Logger.getLogger().debug("目录不存在创建目录");
58                             }  
59                             String path= saveDir + File.separatorChar + fileName;  
60                             Logger.getLogger().debug("文件上传到的路径"+path);
61                             //上传文件  
62                             File uploaderFile = new File(path);  
63                             item.write(uploaderFile);  
64                             resutlstr = fileName;
65                         }
66                         
67                     }  
68                 }  
69             }catch(Exception e){
70                 e.printStackTrace();  
71                 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);    
72             }  
73 //            response.setStatus(HttpServletResponse.SC_OK);  
74 //            response.getWriter().append("Success Upload");  
75         }   
76         return qb.doImport(resutlstr, questionBankId, domainCode, operatorUserAccount);
77     }
View Code

  这个是放在服务层的bo(就是方法的实现)把客户端的 文件上传到服务器端  这里要着重说一下iE和火狐读到的图片格式 是不一样的 (如何要限制文件或者图片格式的话)
    代码不会再服务器端创建文件夹或者路径 那一块代码 有问题   这个方法中的resutlstr只是加密后的文件的名字  在qb.doImport() 方法的实现中有用到

技术分享
private QuestionVo questionVo = new QuestionVo();
    static IQuestionService questionService;
    static IQuestionBankService questionBankService;
    static
    {
        try {
            questionService = (IQuestionService) ServiceFactory.getService(
                    IQuestionService.class, "questionService");
            questionBankService = (IQuestionBankService)ServiceFactory.getService(
                    IQuestionBankService.class,"questionBankService");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
    public String doImport(String fileName, Long questionBankId,String domainCode,String operatorUserAccount)
    {    
        CodeMessage cm = new CodeMessage();
        byte[] bytes =null;        
        
        Logger.getLogger().debug(fileName);
        String downLoadUrl = Configer.getInstance().getProperty("save_xlsUrl");        
        if(StringUtils.isBlank(fileName))
        {
            cm.setCode(400);
            cm.setMessage("文件为空,不能导入");
        }
        else
        {            
            String filepath = downLoadUrl+fileName;            
            File file = new File(filepath);    
            Logger.getLogger().debug("*********************************************************cun******"+file.exists());
            if(null == file)
            {
                cm.setCode(400);
                cm.setMessage("无导入文件,请检查后再操作");
            }
            else
            {
                try {
                    bytes = FileConvertor.getByte(file);
                } catch (Exception e) {                    
                    e.printStackTrace();
                }                
            /*    Long questionBankId = questionVo.getQuestionBankId();
                String domainCode = questionVo.getDomainCode();
                String operatorUserAccount = questionVo.getOperatorUserAccount();    */            
                cm = questionService.doImport(bytes, questionBankId, domainCode, operatorUserAccount);
            }
        }
        
        String jsonResult = JSONConvertor.bean2Json(cm);
        return jsonResult;
    }

}
View Code

    这个也是在服务层的文件的一些属性的做的处理

技术分享
public static byte[] getByte(File file) throws Exception {
        byte[] bytes = null;
        try {
            InputStream is = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = is.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            is.close();
            bos.close();
            bytes = bos.toByteArray();
        }catch(FileNotFoundException e){
            e.printStackTrace();
        } 
        catch (IOException  e) {
            e.printStackTrace();
        }
        return bytes;
    }
View Code

把流文件转化为bytes文件

 

2015-6-2 文件的上传java

标签:

原文地址:http://www.cnblogs.com/w1136060202/p/4546204.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!