图片上传,有预览效果

html:

<div class="touxiang" οnclick="headImageFile.click();">
<div class="touxiang_box" style="position:relative;">
<img  id="image" src="../images/tou.png"><img id="dele" class="deleteImg" src="../images/delete.png">
<input type="hidden" name="headImg" id="headImg" />
</div>
<!-- <input type="hidden" name="" id="upload" οnclick="headImageFile.click();" > -->
<p>点击上传</p>
</div>

<form name="uploadFileHead" id="uploadFileHead" method="post" enctype="multipart/form-data" > 
<input type="file" οnchange="uploadHead()" id="headImageFile" name="fileData" value="开始上传" style="display: none;"/>
<input type="hidden" name="fileDir"  value="salesmanLogo"/>
<input type="hidden" name="size"  value="1000"/>
<input type="hidden" name="norms"  value="200x200"/>
<input type="hidden" name="fileExt"  value="*.jpg|*.jpeg|*.png"/>
</form>


js:

function uploadHead() {
    try {
        var fileName = $("#headImageFile").val();
        // if(typeof(console)!="undefined") console.log(fileName)
        if (fileName == "") {
            myAlert("请选择你要上传的图片");
            return false;
        }
        if (!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(fileName)) {
            myAlert("确认图片格式为:.gif,jpeg,jpg,png");
    return false;
        }
        $("#uploadFileHead").attr("action", "../upload/upload.action");
    } catch(e) {
        if (jsDebugMode == 1) {
            // myAlert(e.name + ":" + e.message);
            autoRefresh();
        }
    }


    $("#uploadFileHead").ajaxUpload({
        // 上传中
        processing: function(pg) {
            uploadingAlert();
        },
        // 上传完毕
        success: function(data) {
        console.log(data);
            try {
                // if(typeof(console)!="undefined") console.log(data)
                data = eval('(' + data + ')');
                if (data.retCode == "1") {
                //var str = "<img id='image' src=\"" + data.returnData + "\"><img class=\"deleteImg\" src=\"../images/delete.png\">";
                    $("#headImg").val(data.returnData);
                    $("#image").attr("src", data.returnData);
                  //  $(".touxiang_box").append($(str));
                    $("#dele").show();
                    closeMyAlert();
                } else {
                    myAlert("图片上传失败");
                }


            } catch(e) {
                if (jsDebugMode == 1) {
                    // myAlert(e.name + ":" + e.message);
                    autoRefresh();
                }
            }
        },
        error: function(data) {
            // data = eval('(' + data + ')');
                alert("上传失败:" + data);
        }
    })
}


action:

import java.io.File;


import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;


import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;


import cn.zhuoqin.platform.util.JsonUtil;
import cn.zhuoqin.platform.web.AjaxResData;
import cn.zhuoqin.platform.web.BaseAction;
import cn.zhuoqin.thirdparty.kadan.upload.model.UploadArgsBean;
import cn.zhuoqin.thirdparty.kadan.upload.service.UploadService;


@Namespace("/upload")
@Action(value ="upload")
@Results({ @Result(name = BaseAction.SUCCESS, type = "json") })
public class UploadAction  extends ActionSupport implements ModelDriven{


private static final long serialVersionUID = 1L;
public UploadArgsBean uploadArgsBean;
public File fileData;
@Autowired
private  UploadService uploadService;




public boolean checkFile() {
return false;


}
@Override
public Object getModel() {
// TODO Auto-generated method stub
if(uploadArgsBean == null){
uploadArgsBean = new UploadArgsBean();
     }
     return uploadArgsBean;
}




public File getFileData() {
return fileData;
}
public void setFileData(File fileData) {
this.fileData = fileData;
}
public UploadArgsBean getUploadArgsBean() {
return uploadArgsBean;
}
public void setUploadArgsBean(UploadArgsBean uploadArgsBean) {
this.uploadArgsBean = uploadArgsBean;
}


@Override
public String execute(){
AjaxResData ag =  null;
try{
ag = uploadService.upload(fileData, uploadArgsBean);
}catch(Exception e){
e.printStackTrace();
}finally{
JsonUtil.renderText(ag);
}
return null;


}


}

service:

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;


import java.util.Date;
import java.util.UUID;


import javax.imageio.ImageIO;


import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;


import cn.zhuoqin.platform.util.DataUtil;
import cn.zhuoqin.platform.util.FileUtils;
import cn.zhuoqin.platform.util.ImageCompressUtils;
import cn.zhuoqin.platform.web.AjaxResData;
import cn.zhuoqin.thirdparty.kadan.upload.model.CommonConfig;
import cn.zhuoqin.thirdparty.kadan.upload.model.UploadArgsBean;
import cn.zhuoqin.thirdparty.kadan.upload.service.UploadService;




@Service
public class UploadServiceImpl implements UploadService {
private static Logger logger = LoggerFactory.getLogger(UploadService.class);
@Autowired
private CommonConfig commonConfig;


public String getPartFilePath(String folder, String fileName) {
Date date = new Date();
StringBuilder sb = new StringBuilder();
sb.append(folder);
sb.append('/');
// sb.append(fileName);
sb.append(DataUtil.convertDateToString(date, "yyyyMMdd"));
sb.append(DataUtil.convertDateToString(date, "HHmmssSSS"));
sb.append(UUID.randomUUID().toString().replace("-", ""));
// sb.append(RandomStringUtils.randomAlphanumeric(3));
// sb.append(fileName.substring(fileName.lastIndexOf(".")));
return sb.toString();
}


public void doCutFile(File sourceFile, File saveFile, int width, int height) throws Exception {
// File sourceFile = new File(commonConfig.getImageUploadPath(),
// sourcePath);
logDebug("8.1、FileUtils.createDirs(saveFile.getParent()); 前");
FileUtils.createDirs(saveFile.getParent());
logDebug("8.1、FileUtils.createDirs(saveFile.getParent()); 后");
BufferedImage srcImage = ImageIO.read(sourceFile);
logDebug("8.2、BufferedImage srcImage = ImageIO.read(sourceFile);");
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
logDebug("8.3、BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);");
image.getGraphics().drawImage(srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
logDebug("8.4、image.getGraphics().drawImage(srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);");
FileOutputStream out = new FileOutputStream(saveFile);
logDebug("8.5、FileOutputStream out = new FileOutputStream(saveFile);");


if (commonConfig.getImageCompressMode().trim().toLowerCase().equals("JPEGImageEncoder".toLowerCase())) {
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
logDebug("8.6、JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);");
encoder.encode(image);
logDebug("8.7、encoder.encode(image);");
out.flush();
logDebug("8.8、out.flush();");
if (out != null) {
out.close();
}
} else {
ImageCompressUtils.saveAsJPEG(100, image, 1, out);
if (out != null) {
out.close();
}
}


if (logger.isDebugEnabled()) {
logDebug("8.9、out.close();");
}
}


@Override
public AjaxResData upload(File file, UploadArgsBean bean) {
Boolean result = false;// 上传是否成功
String msg = "";// 提示信息
String filePath = "";// 保存数据库中的路径,图片为原图片
File saveFile = null;// 全路径文件
String uploadFilePath = "";// 保存到数据库中的路径,图片被压缩后的
AjaxResData ard = new AjaxResData();
/*
* InputStream is = null; OutputStream os = null;
*/
try {
if (logger.isDebugEnabled()) {
logDebug("0、getImageBaseUrl=" + commonConfig.getImageBaseUrl());
logDebug("0、getImageTempDisk=" + commonConfig.getImageTempDisk());
logDebug("0、getImageUploadPath=" + commonConfig.getImageUploadPath());
}
logDebug("1、进入文件接收处理流程");
String fileName = "";
if (StringUtils.isNotEmpty(bean.getFileDataFileName())) {
fileName = bean.getFileDataFileName().substring(0, bean.getFileDataFileName().lastIndexOf("."));
}
logDebug("2、文件名称:" + fileName);
long fileSize = file.length();
logDebug("3、文件大小:" + fileSize);
/*
* if (Float.valueOf(bean.getSize()) * 1000 < fileSize) {//验证大小 msg
* = "上传文件大小不能超过" + bean.getSize() + "KB."; return ard; }
*/
// 人为修改文件后缀上传,或者直接上传没有后缀的文件
int len = bean.getFileDataFileName().lastIndexOf(".");
String sufix = bean.getFileDataFileName().substring(len).toLowerCase();


logDebug("4、文件后缀:" + sufix);
if (len == -1) {
msg = "不能上传没有扩展名的文件!";
logDebug("5、" + msg);
return ard;
} else if (!bean.getFileExt().equals("*.*") && !bean.getFileExt().contains(sufix)) {


msg = "上传文件格式只能为 " + bean.getFileExt();
logDebug("6、" + msg);
return ard;
}


String[] arr = bean.getNorms().split("x");
int width = Integer.valueOf(arr[0]);
int height = Integer.valueOf(arr[1]);


filePath = "/" + this.getPartFilePath(bean.getFileDir(), fileName);
filePath = filePath + "_" + width + "x" + height + sufix;


logDebug("7、filePath=" + filePath + ".ImageUploadPath=" + commonConfig.getImageUploadPath());


saveFile = new File(commonConfig.getImageUploadPath(), filePath);


logDebug("8、ImageBaseUrl=" + saveFile.getAbsolutePath());


this.doCutFile(file, saveFile, width, height);


logDebug("9、ImageBaseUrl=" + commonConfig.getImageBaseUrl());


filePath = commonConfig.getImageBaseUrl() + filePath;


logDebug("10、return path=" + filePath);


result = true;
} catch (Exception e) {
String rlt = "";
try {
rlt = JSONUtil.serialize(e);
} catch (Exception ex) {
logError("文件上传===", ex);
}


logDebug("11、文件上传出现异常:", e);
logDebug("12、文件上传出现异常:" + rlt);


try {
if (saveFile != null) {
FileUtils.deleteFile(saveFile.getAbsolutePath());
}
} catch (Exception inner) {
try {
rlt = JSONUtil.serialize(inner);
} catch (Exception ex) {
logError("文件上传===", ex);
}


logDebug("13、删除文件出现异常:", inner);
logDebug("13、删除文件出现异常:", rlt);
}


} finally {
/*
* IOUtils.closeQuietly(is); IOUtils.closeQuietly(os);
*/
ard.setReturnData(filePath);
ard.setMessage(msg);
ard.setRetCode(result ? "1" : "0");
String rlt = "";
try {
rlt = JSONUtil.serialize(ard);
} catch (Exception ex) {
logError("14、文件上传===", ex);
}
logDebug("15、文件上传===", ard);
logDebug("15、文件上传===" + rlt);
}


return ard;
}


private void logDebug(String message) {
try {
if (logger.isDebugEnabled()) {
logger.debug(message);
}
} catch (Exception ex) {
}
}


private void logDebug(String message, Object obj) {
try {
if (logger.isDebugEnabled()) {
logger.debug(message, obj);
}
} catch (Exception ex) {
}
}


private void logError(String message, Exception ex) {
try {
if (logger.isErrorEnabled()) {
logger.error(message, ex);
}
} catch (Exception iex) {
}
}


}


CommonConfig:

public class CommonConfig {
/**
* 上传图片的存放路径
*/
private String imageTempDisk;


/**
* 上传图片前缀地址
*/
private String imageUploadPath;
/**
* 上传图片URL基地址
*/
private String imageBaseUrl;


/**
* 压缩方式
*/
private String imageCompressMode;


public String getImageTempDisk() {
return imageTempDisk;
}


public void setImageTempDisk(String imageTempDisk) {
this.imageTempDisk = imageTempDisk;
}


public String getImageUploadPath() {
return imageUploadPath;
}


public void setImageUploadPath(String imageUploadPath) {
this.imageUploadPath = imageUploadPath;
}


public String getImageBaseUrl() {
return imageBaseUrl;
}


public void setImageBaseUrl(String imageBaseUrl) {
this.imageBaseUrl = imageBaseUrl;
}


public String getImageCompressMode() {
return imageCompressMode;
}


public void setImageCompressMode(String imageCompressMode) {
this.imageCompressMode = imageCompressMode;
}


}


ImageCompressUtils:

public class ImageCompressUtils {


private static Logger logger = LoggerFactory.getLogger(ImageCompressUtils.class);


/**
* 图片压缩测试

* @param args
*/
public static void main(String args[]) {
// 对一个文件进行压缩处理
String url = "/var/upload_bak/";
String name = "31273618df16f1ab32e76c06c2f35852.jpg";
img_change(url, name);
}


private static void img_change(String url, String name) {
Tosmallerpic(url, new File(url + name), "_middle", name, 188, 165, (float) 0.7);
Tosmallerpic(url, new File(url + name), "_small", name, 45, 45, (float) 0.7);
Tosmallerpic(url, new File(url + name), "_smaller", name, 116, 100, (float) 0.7);
}


/**

* @param f
*            图片所在的文件夹路径
* @param file
*            图片路径
* @param ext
*            扩展名
* @param n
*            图片名
* @param w
*            目标宽
* @param h
*            目标高
* @param per
*            百分比
*/
private static void Tosmallerpic(String f, File file, String ext, String n, int w, int h, float per) {
Image src;
try {
src = javax.imageio.ImageIO.read(file); // 构造Image对象


String img_midname = f + n.substring(0, n.indexOf(".")) + ext + n.substring(n.indexOf("."));
int old_w = src.getWidth(null); // 得到源图宽
int old_h = src.getHeight(null);
int new_w = 0;
int new_h = 0; // 得到源图长


double w2 = (old_w * 1.00) / (w * 1.00);
double h2 = (old_h * 1.00) / (h * 1.00);


// 图片跟据长宽留白,成一个正方形图。
BufferedImage oldpic;
if (old_w > old_h) {
oldpic = new BufferedImage(old_w, old_w, BufferedImage.TYPE_INT_RGB);
} else {
if (old_w < old_h) {
oldpic = new BufferedImage(old_h, old_h, BufferedImage.TYPE_INT_RGB);
} else {
oldpic = new BufferedImage(old_w, old_h, BufferedImage.TYPE_INT_RGB);
}
}
Graphics2D g = oldpic.createGraphics();
g.setColor(Color.white);
if (old_w > old_h) {
g.fillRect(0, 0, old_w, old_w);
g.drawImage(src, 0, (old_w - old_h) / 2, old_w, old_h, Color.white, null);
} else {
if (old_w < old_h) {
g.fillRect(0, 0, old_h, old_h);
g.drawImage(src, (old_h - old_w) / 2, 0, old_w, old_h, Color.white, null);
} else {
// g.fillRect(0,0,old_h,old_h);
g.drawImage(src.getScaledInstance(old_w, old_h, Image.SCALE_SMOOTH), 0, 0, null);
}
}
g.dispose();
src = oldpic;
// 图片调整为方形结束
if (old_w > w)
new_w = (int) Math.round(old_w / w2);
else
new_w = old_w;
if (old_h > h)
new_h = (int) Math.round(old_h / h2);// 计算新图长宽
else
new_h = old_h;
BufferedImage image_to_save = new BufferedImage(new_w, new_h, BufferedImage.TYPE_INT_RGB);
image_to_save.getGraphics().drawImage(src.getScaledInstance(new_w, new_h, Image.SCALE_SMOOTH), 0, 0, null);
FileOutputStream fos = new FileOutputStream(img_midname); // 输出到文件流


// 新的方法
saveAsJPEG(100, image_to_save, per, fos);


fos.close();
} catch (IOException ex) {
// Logger.getLogger(Img_Middle.class.getName()).log(Level.SEVERE,
// null, ex);
}
}


/**
* 以JPEG编码保存图片

* @param dpi
*            分辨率
* @param image_to_save
*            要处理的图像图片
* @param JPEGcompression
*            压缩比
* @param fos
*            文件输出流
* @throws IOException
*/
public static void saveAsJPEG(Integer dpi, BufferedImage image_to_save, float JPEGcompression, FileOutputStream fos) throws IOException {


// Image writer
JPEGImageWriter imageWriter = (JPEGImageWriter) ImageIO.getImageWritersBySuffix("jpg").next();
logger.error("8.6、JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);");
ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
logger.error("8.7、ImageOutputStream ios = ImageIO.createImageOutputStream(fos);");
imageWriter.setOutput(ios);
logger.error("8.8、imageWriter.setOutput(ios);");
// and metadata
IIOMetadata imageMetaData = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(image_to_save), null);
logger.error("8.9、IIOMetadata imageMetaData = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(image_to_save), null);");
if (dpi != null && !dpi.equals("")) {
// new metadata
Element tree = (Element) imageMetaData.getAsTree("javax_imageio_jpeg_image_1.0");
logger.error("8.10、Element tree = (Element) imageMetaData.getAsTree(\"javax_imageio_jpeg_image_1.0\");");
Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0);
logger.error("8.11、Element jfif = (Element) tree.getElementsByTagName(\"app0JFIF\").item(0);");
jfif.setAttribute("Xdensity", Integer.toString(dpi));
logger.error("8.12、jfif.setAttribute(\"Xdensity\", Integer.toString(dpi));");
jfif.setAttribute("Ydensity", Integer.toString(dpi));
logger.error("8.13、jfif.setAttribute(\"Ydensity\", Integer.toString(dpi));");
}


if (JPEGcompression >= 0 && JPEGcompression <= 1f) {
// new Compression
JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
logger.error("8.15、JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();");
jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
logger.error("8.16、jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);");
jpegParams.setCompressionQuality(JPEGcompression);
logger.error("8.17、jpegParams.setCompressionQuality(JPEGcompression);");
}
// new Write and clean up
imageWriter.write(imageMetaData, new IIOImage(image_to_save, null, null), null);
logger.error("8.18、imageWriter.write(imageMetaData, new IIOImage(image_to_save, null, null), null);");
ios.close();
logger.error("8.19、ios.close();");
imageWriter.dispose();
logger.error("8.20、imageWriter.dispose();");
}


}

FileUtils:

public class FileUtils {
    private static Logger log = LoggerFactory.getLogger(FileUtils.class);


    /**
     * <根据路径获取BufferedReader >
     * 
     * @param filePath
     * @return
     *         BufferedReader
     * @throws
     */
    public static BufferedReader getBufferedReader(String filePath) {
        return getBufferedReader(filePath, null);
    }


    /**
     * <根据路径获取BufferedReader,指定编码读取文件 >
     * 
     * @param filePath
     * @param encoding
     * @return
     *         BufferedReader
     * @throws
     */
    public static BufferedReader getBufferedReader(String filePath, String encoding) {
        BufferedReader br = null;
        try {
            if (StringUtils.trimToEmpty(encoding).isEmpty()) {
                br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
            } else {
                br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), encoding));
            }
        } catch (UnsupportedEncodingException e) {
            log.error(e.toString());
        } catch (FileNotFoundException e) {
            log.error(e.toString());
        }
        return br;
    }


    /**
     * <获取zip reader>
     * 
     * @param zipFile
     * @param encoding
     * @return
     */
    /*public static BufferedReader getZipBufferedReader(ZipFile zipFile, String encoding) {
        BufferedReader br = null;
        try {
            Enumeration<ZipEntry> em = zipFile.getEntries();
            ZipEntry zipEntry = null;
            while (em.hasMoreElements()) {
                zipEntry = em.nextElement();
                if (!zipEntry.isDirectory()) {
                    break;
                }
            }
            if (StringUtils.trimToEmpty(encoding).isEmpty()) {
                br = new BufferedReader(new InputStreamReader(zipFile.getInputStream(zipEntry)));
            } else {
                br = new BufferedReader(new InputStreamReader(zipFile.getInputStream(zipEntry), encoding));
            }
        } catch (Exception e) {
            log.error(e.toString());
        }
        return br;
    }*/


    /**
     * <关闭流 >
     * 
     * @param br
     *            void
     * @throws
     */
    public static void closeReader(BufferedReader br) {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                log.error(e.toString());
            }
        }
    }


    /**
     * <根据路径获取File >
     * 
     * @param filePath
     * @return
     *         File
     * @throws
     */
    public File getFile(String filePath) {
        return new File(filePath);
    }


    /**
     * ;
     * <获取 文件后缀 >
     * 
     * @param fileName
     * @return
     *         String
     * @throws
     */
    public static String getFileSuffix(String fileName) {
        String suffix = "";
        String file = StringUtils.trimToEmpty(fileName);
        if (!file.isEmpty()) {
            int pos = file.lastIndexOf(".");
            if (pos > 0) {
                suffix = file.substring(file.lastIndexOf(".") + 1);
            }
        }
        return suffix.toLowerCase();
    }


    /**
     * <判断 当前文件名的后缀是否符合指定要求 >
     * 
     * @param sourceSuffix
     * @param fileName
     * @return
     *         boolean
     * @throws
     */
    public static boolean checkSuffix(String sourceSuffix, String fileName) {
        boolean result = false;
        String source = StringUtils.trimToEmpty(sourceSuffix).toLowerCase();
        String[] suffixArray = source.split("\\|");
        String dest = getFileSuffix(fileName).toLowerCase();
        if (!dest.isEmpty()) {
            for (String suffix : suffixArray) {
                if (suffix.equals(dest)) {
                    result = true;
                    break;
                }
            }
        }
        return result;
    }


    /**
     * <创建目录 >
     * 
     * @param path
     *            void
     * @throws
     */
    public static void createDirs(String path) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
    }


    /**
     * <删除文件 >
     * 
     * @param path
     *            void
     * @throws
     */
    public static void deleteFile(String path) {
        if (path != null) {
            File file = new File(path);
            if (file.exists()) {
                file.delete();
            }
        }
    }


    /**
     * <加密保存文件>
     * 
     * @param in
     *            输入流
     * @param destFile
     *            目标保存文件
     * @param keyword
     *            加密字串
     * @throws Exception
     *             void
     * @throws
     */
    public static void encrypt(InputStream in, File destFile, String keyword) throws Exception {
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, getKey(keyword));
        OutputStream out = new FileOutputStream(destFile);
        CipherInputStream cis = new CipherInputStream(in, cipher);
        byte[] buffer = new byte[1024];
        int r;
        while ((r = cis.read(buffer)) > 0) {
            out.write(buffer, 0, r);
            out.flush();
        }
        if (cis != null) {
            cis.close();
        }
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
    }


    /**
     * <下载文件 >
     * 
     * @param out
     *            输出流
     * @param sourceFile
     *            源文件
     * @param keyword
     *            加密字串
     * @throws Exception
     *             void
     * @throws
     */
    public static void decrypt(OutputStream out, File sourceFile, String keyword) throws Exception {
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, getKey(keyword));
        InputStream in = new FileInputStream(sourceFile);
        CipherOutputStream cos = new CipherOutputStream(out, cipher);
        byte[] buffer = new byte[1024];
        int r;
        while ((r = in.read(buffer)) >= 0) {
            cos.write(buffer, 0, r);
            cos.flush();
        }
        if (cos != null) {
            cos.close();
        }
        if (out != null) {
            out.close();
        }
        if (in != null) {
            in.close();
        }
    }


    /**
     * <获取解密的inputstream >
     * 
     * @param sourceFile
     *            源文件
     * @param keyword
     *            解密字串
     * @return
     * @throws Exception
     *             InputStream
     * @throws
     */
    private static InputStream getCipherInputStream(String sourceFile, String keyword) throws Exception {
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, getKey(keyword));
        return new CipherInputStream(new FileInputStream(new File(sourceFile)), cipher);
    }


    /**
     * <获取读取解密文件的Reader >
     * 
     * @param sourceFile
     *            源文件
     * @param keyword
     *            解密字串
     * @param encoding
     *            文件编码
     * @return
     *         BufferedReader
     * @throws
     */
    public static BufferedReader getBufferedReader(String sourceFile, String keyword, String encoding) {
        BufferedReader br = null;
        try {
            if (StringUtils.trimToEmpty(encoding).isEmpty()) {
                br = new BufferedReader(new InputStreamReader(getCipherInputStream(sourceFile, keyword)));
            } else {
                br = new BufferedReader(new InputStreamReader(getCipherInputStream(sourceFile, keyword), encoding));
            }
        } catch (Exception e) {
            log.error(e.toString());
        }
        return br;
    }


    /**
     * < 获取加密key>
     * 
     * @param keyword
     * @return
     *         key
     * @throws
     */
    private static Key getKey(String keyword) {
        Key key = null;
        try {
            KeyGenerator generator = KeyGenerator.getInstance("DES");
            // 防止linux下 随机生成key
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(keyword.getBytes());
            generator.init(56, secureRandom);
            key = generator.generateKey();
            generator = null;
        } catch (Exception e) {
            log.error(e.toString());
        }
        return key;
    }


    /**
     * <获取压缩文件中的原始文件对象>
     * 
     * @param zipFileName
     * @return
     */
    /*public static String getZipEntryName(String zipFileName) {
        String entryName = null;
        ZipFile zipFile = buildZipFile(zipFileName);
        if (zipFile != null) {
            Enumeration<ZipEntry> em = zipFile.getEntries();
            while (em.hasMoreElements()) {
                ZipEntry zipEntry = em.nextElement();
                if (!zipEntry.isDirectory()) {
                    if (entryName == null) {
                        entryName = zipEntry.getName();
                    } else {
                        entryName = null;
                        break;// 超过1个文件,直接中断循环
                    }
                }
            }
            ZipFile.closeQuietly(zipFile);
        }
        return entryName;
    }
*/
    /**
     * <生成ZipFile对象>
     * 
     * @param zipFileName
     * @return
     */
    /*private static ZipFile buildZipFile(String zipFileName) {
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(zipFileName, "GBK");
        } catch (IOException e) {
            log.error(e.toString());
        }
        return zipFile;
    }*/


    /**
     * <获取临时zip生成路径>
     * 
     * @param zipFilePath
     * @return
     */
    public static String getTmpZipFilePath(String zipFilePath) {
        return zipFilePath == null ? zipFilePath : zipFilePath.replace(".zip", "_.zip");
    }


    /**
     * 获取指定扩展名的文件
     * 
     * @param filePath
     * @param extName
     * @return
     */
    public static String getFileName(String filePath, String extName) {
        String fileName = "";
        File file = new File(filePath);
        if (!file.exists()) {
            return fileName;
        }
        if (!file.isDirectory()) {
            return fileName;
        }
        String[] tempList = file.list();
        File temp = null;
        if (!filePath.endsWith(File.separator)) {
            filePath += File.separator;
        }
        for (int i = 0; i < tempList.length; i++) {
            temp = new File(filePath + tempList[i]);
            if (temp.isFile()) {
                if (getFileExt(temp.getPath()).toUpperCase().equals(extName.toUpperCase())) {
                    fileName = temp.getPath();
                    break;
                }
            }
            if (temp.isDirectory()) {
                fileName = getFileName(filePath + tempList[i], extName);
                if (!fileName.equals("")) {
                    break;
                }
            }
        }
        return fileName;
    }


    /**
     * 取文件扩展名
     * 
     * @param fileName
     * @return
     */
    public static String getFileExt(String fileName) {
        if (fileName.indexOf(".") == -1) {
            return "";
        }
        String ext = fileName;
        while (ext.indexOf(".") >= 0) {
            ext = ext.substring(ext.indexOf(".") + 1);
        }
        return ext;
    }


    /**
     * 创建新文件
     * 
     * @param fileFullName
     * @param fileContent
     * @param encoding
     * @return
     */
    public static boolean createFile(String fileFullName, String fileContent, String encoding) {
        try {
            String filePath = fileFullName;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            if (!myFilePath.exists()) {
                myFilePath.createNewFile();
            }
            OutputStream out = new FileOutputStream(myFilePath);
            BufferedWriter rd = new BufferedWriter(new OutputStreamWriter(out, encoding));
            rd.write(fileContent);
            rd.close();
            out.close();
            return true;
        } catch (Exception ex) {
            log.error(ex.toString());
        }
        return false;
    }
}


UploadArgsBean:
public class UploadArgsBean {


private String fileDataFileName;


/**
* int size:(上传文件最大size,单位KB)
*/
private String size;


/**
* String fileExt:(文件扩展名)
*/
private String fileExt;


/**
* String norms:(文件上传规格,如30x40)
*/
private String norms;


/**
* String fileDir:(文件上传子目录)
*/
private String fileDir;


/**
* boolean imageType:(是否图片上传)
*/
private boolean imageType;


/**
* boolean cutFile:(是否图片切割)
*/
private boolean cutFile;


/**
* String filePath:(文件上传后的路径,即保存数据库的相对路径)
*/
private String filePath;




public boolean isImageType() {
return imageType;
}


public void setImageType(boolean imageType) {
this.imageType = imageType;
}


public String getFileDir() {
return fileDir;
}


public void setFileDir(String fileDir) {
this.fileDir = fileDir;
}


public String getNorms() {
return norms;
}


public void setNorms(String norms) {
this.norms = norms;
}


public boolean isCutFile() {
return cutFile;
}


public void setCutFile(boolean cutFile) {
this.cutFile = cutFile;
}


public String getFilePath() {
return filePath;
}


public void setFilePath(String filePath) {
this.filePath = filePath;
}


public String getSize() {
return size;
}


public void setSize(String size) {
this.size = size;
}


public String getFileExt() {
return fileExt;
}


public void setFileExt(String fileExt) {
this.fileExt = fileExt;
}


public String getFileDataFileName() {
return fileDataFileName;
}


public void setFileDataFileName(String fileDataFileName) {
this.fileDataFileName = fileDataFileName;
}


}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值