xhEditor编缉器使用传,解决火狐不能上传文件的问题

 

package com.*.servlet;

 

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.io.PrintWriter;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.swing.text.html.HTMLDocument.Iterator;

 

import org.apache.commons.fileupload.DiskFileUpload;

import org.apache.commons.fileupload.FileItem;

 

import com.sq.hrm.util.Util;

 

public class Upload extends HttpServlet {

//初始路径

private static String baseDir="";

//定义 新闻系统上传路径

private static String newsUploadDir="/news/upload/";

//定义 体系文件上传路径

private static String filesUploadDir="/files/upload/";

//定义 其他文件上传路径

private static String otherUploadDir="/upload/";

//上传文件类型,默认为空,所有文件都不能传

private static String fileExt=",zip,rar,txt,doc,xls,ppt,docx,xlsx,pptx,flv,jpg,jpeg,gif,png,bmp,swf,wmv,avi,wma,mp3,mid,";

//上传文件大小 ,默认为0

private static long maxSize=1024*1024*20l;//最大允许上传20M文件

//文件存放模式,0-不建目录;1-按天存放;2-按月存放;3-按扩展名存放

private static String dirType="2";

 

/**

* Constructor of the object.

*/

public Upload() {

super();

}

 

/**

* Destruction of the servlet.

*/

public void destroy() {

super.destroy(); // Just puts "destroy" string in log

// Put your code here

}

 

/**

* The doPost method of the servlet.

*

* This method is called when a form has its tag value method equals to post.

* @param request the request send by the client to the server

* @param response the response send by the server to the client

* @throws ServletException if an error occurred

* @throws IOException if an error occurred

*/

public void service(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html;charset=GBK");

response.setHeader("Cache-Control", "no-cacha");

String base=request.getParameter("base");

String id=request.getParameter("id");

String err="";

String newFileName="";

/*HTML5兼容*/

if ("application/octet-stream".equals(request.getContentType())) {

try {

                String dispoString = request.getHeader("Content-Disposition");

                int iFindStart = dispoString.indexOf("name=/"")+6;

                int iFindEnd = dispoString.indexOf("/"", iFindStart);

 

                iFindStart = dispoString.indexOf("filename=/"")+10;

                iFindEnd = dispoString.indexOf("/"", iFindStart);

                String sFileName = dispoString.substring(iFindStart, iFindEnd);

 

                int i = request.getContentLength();

                byte buffer[] = new byte[i];

                int j = 0;

                /*获取表单的上传文件*/

                while(j < i) { 

                    int k = request.getInputStream().read(buffer, j, i-j);

                    j += k;

                }

                /*文件是否为空*/

                if (buffer.length == 0) { 

                    printInfro(response, "上传文件不能为空", "");

                    return;

                }

 

                /*检查文件大小*/

                if (maxSize > 0 && buffer.length > maxSize) { 

                    printInfro(response, "上传文件的大小超出限制", "");

                    return;

                }

 

                String filePathString = getSaveFilePath(sFileName,request,response);

 

                /*检查文件类型 */

                if("不允许上传此类型的文件".equals(filePathString)) return; 

 

                String saveFile=this.getServletConfig().getServletContext().getRealPath("") + filePathString;

                System.out.println("saveFile:"+saveFile);

 

                OutputStream out=new BufferedOutputStream(new FileOutputStream(saveFile,true));

                out.write(buffer);

                out.close(); 

                newFileName = request.getContextPath() + filePathString;

                System.out.println("newFileName:"+newFileName);

            } catch (Exception ex) {

                System.out.println(ex.getMessage());

                newFileName = "";

                err = "错误: " + ex.getMessage();

            }

}else{

/*其他*/

DiskFileUpload upload=new DiskFileUpload();

try{

List items=upload.parseRequest(request);

Map fields=new HashMap();

java.util.Iterator iter=items.iterator();

while(iter.hasNext()){

FileItem item=(FileItem)iter.next();

if(item.isFormField()){

fields.put(item.getFieldName(), item.getString());

}else{

fields.put(item.getFieldName(), item);

}

}

/*获取表单的上传文件*/

FileItem uploadFile=(FileItem)fields.get("filedata");

/*获取文件上传路*/

String fileNameLong=uploadFile.getName();

/*取得文件扩展名*/

String extensionName=fileNameLong.substring(fileNameLong.lastIndexOf(".")+1).toLowerCase();

/*检查文件类型*/

if(fileExt.toLowerCase().indexOf(","+extensionName+",")<0){

printInfro(response,"不允许上传此类型文件","");

}

/*检查文件大小*/

if(maxSize>0 && uploadFile.getSize()>maxSize){

printInfro(response,"上传文件大小超出了系统限制","");

return;

}

/*上传文件保存存方式 */

String fileFolder="";

if(dirType.equalsIgnoreCase("1"))fileFolder=new SimpleDateFormat("yyyyMMdd").format(new Date());

if(dirType.equalsIgnoreCase("2"))fileFolder=new SimpleDateFormat("yyyyMM").format(new Date());

if(dirType.equalsIgnoreCase("3"))fileFolder=extensionName.toLowerCase();

/*选择初始目录*/

if(base.equalsIgnoreCase("news")){

baseDir=newsUploadDir;

}else if(base.equalsIgnoreCase("files")){

baseDir=filesUploadDir;

}else{

baseDir=otherUploadDir;

}

/*文件存储的相对路径*/

String saveDirPath=baseDir+fileFolder+"/";

/*文件在服务器上存储的绝对路径*/

String saveFilePath=this.getServletConfig().getServletContext().getRealPath("")+saveDirPath;

//System.out.println("saveFilePath:"+saveFilePath);

/*构建文件目录及目录文件*/

File fileDir=new File(saveFilePath);

if(!fileDir.exists())fileDir.mkdirs();

/*重命名文件*/

String fileName=Util.TransDate();

File saveFile=new File(saveFilePath+fileName+"."+extensionName);

/*存储上传文件*/

if("".equals(id)||id==null||id.length()!=18){

printInfro(response,"对不起,你没有授权!","");

}else{

uploadFile.write(saveFile);

}

/*返回文件路径,从虚拟目录开始*/

newFileName=request.getContextPath()+saveDirPath+fileName+"."+extensionName;

//System.out.println("newFileName:"+newFileName);

}catch(Exception ex){

System.out.println(ex.getMessage());

newFileName="";

err="错误:"+ex.getMessage();

}

}

printInfro(response,err,newFileName);

}

public void printInfro(HttpServletResponse response,String err,String newFileName)

throws ServletException, IOException {

PrintWriter out=response.getWriter();

out.println("{/"err/":/""+err+"/",/"msg/":/""+newFileName+"/"}");

out.flush();

out.close();

}

public String getSaveFilePath(String sFileName, HttpServletRequest request,HttpServletResponse response)

throws IOException {

String base=request.getParameter("base");

String id=request.getParameter("id");

/*获取文件扩展名 */

String extensionName = sFileName.substring(sFileName.lastIndexOf(".") + 1); 

        /*检查文件类型*/

        if (fileExt.toLowerCase().indexOf("," + extensionName.toLowerCase()+ ",") < 0) {

         try {

printInfro(response, "不允许上传此类型的文件", "");

} catch (ServletException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

         return "不允许上传此类型的文件";

        }

 

        /* 0:不建目录, 1:按天存入目录, 2:按月存入目录, 3:按扩展名存目录.建议使用按天存。*/

        String fileFolder = ""; 

        if (dirType.equalsIgnoreCase("1")) fileFolder = new SimpleDateFormat("yyyyMMdd").format(new Date());

        if (dirType.equalsIgnoreCase("2")) fileFolder = new SimpleDateFormat("yyyyMM").format(new Date());

        if (dirType.equalsIgnoreCase("3")) fileFolder = extensionName.toLowerCase();

 

        /*选择初始目录*/

if(base.equalsIgnoreCase("news")){

baseDir=newsUploadDir;

}else if(base.equalsIgnoreCase("files")){

baseDir=filesUploadDir;

}else{

baseDir=otherUploadDir;

}

        //文件存储的相对路径

        String saveDirPath = baseDir + fileFolder + "/"; 

        //文件存储在容器中的绝对路径

        String saveFilePath = this.getServletConfig().getServletContext().getRealPath("") + saveDirPath; 

 

        //构建文件目录以及目录文件

        File fileDir = new File(saveFilePath); 

        if (!fileDir.exists())fileDir.mkdirs();

 

        /*重命名文件*/

String fileName=Util.TransDate(); 

        return saveDirPath + fileName + "." + extensionName;

    }

 

/**

* Initialization of the servlet.

*

* @throws ServletException if an error occurs

*/

public void init() throws ServletException {

// Put your code here

}

 

}

 

你可能感兴趣的:(xhEditor编缉器使用传,解决火狐不能上传文件的问题)