上传下载code摘抄
============================================================================================================================ /** * 上传附件 * * @param folder 描述 * @param synergyId 单id * @param file 上传的文件 * @param request * @return * @throws CRMException */ @ResponseBody @RequestMapping(value = "/upload_file", method = {RequestMethod.GET, RequestMethod.POST}) public CRMResponse uploadFile(@RequestParam(value = "synergyId", required = false) String synergyId, @RequestParam(value = "folder", required = false) String folder, @RequestParam(value = "fileType",required = true)String fileType, @RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) throws CRMException { CRMResponse $response = new CRMResponse(); // 验证参数: 附件 ParameterValidator.notNull(file, "附件"); // 验证参数: HTTP请求 ParameterValidator.notNull(request, "HTTP请求"); //代理接口 $response.setData(synergyProxy.uploadSynergyFile(synergyId, folder, fileType, file, request)); return $response; } ===================================================================================================================== private static final String[] IMAGE_TYPE = {".jpg",".png",".gif",".svg",".bmp",".jpeg"}; private static final String RELATIVE_PATH_BIG = "/synergyFile/file/big/"; private static final String RELATIVE_PATH_SMALL = "/synergyFile/image/small/"; @Override public FilePath uploadSynergyFile(String synergyId, String folder,String fileType, MultipartFile multipartFile, HttpServletRequest request)throws CRMException{ if (StringUtils.isNotBlank(synergyId)) { if (synergyService.weatherHasClosed(Long.valueOf(synergyId))) { throw new CRMException("***已经被创建者关闭"); } } // 文件名称 String fileName = multipartFile.getOriginalFilename(); // 文件后缀 String suffix = fileName.substring(fileName.lastIndexOf(".")); // 加密后文件名称 fileName = "s"+DigestUtils.md5Hex(fileName + System.currentTimeMillis()) + suffix; // 文件路径 String filePath = request.getSession().getServletContext().getRealPath("../"); // 保存文件 File dest = new File(filePath+RELATIVE_PATH_BIG,fileName); if (!dest.exists()) { dest.mkdirs(); } try { //保存文件 multipartFile.transferTo(dest); //如过是图片,压缩保存小图 if (ifContains(IMAGE_TYPE,fileType)) { File small = new File(filePath+RELATIVE_PATH_SMALL); if (!small.exists()) { small.mkdirs(); } ImageZipUtil imageZipUtil = new ImageZipUtil(); imageZipUtil.compressPic(dest, filePath + RELATIVE_PATH_SMALL, fileName, 300, 320, true); } } catch (IllegalStateException | IOException e) { throw new CRMException("保存文件异常", e); } FilePath path = new FilePath(); path.setId(null); path.setPath(RELATIVE_PATH_BIG+fileName); return path; } =================================================================================================================== /** * 下载附件 * * @param request * @param response * @param fileName 附件名称 * @param realFileName 真实附件名称 * @return * @throws CRMException */ @RequestMapping(value = "/download_file", method = {RequestMethod.GET, RequestMethod.POST}) public String downloadFile(@RequestParam(value = "realFileName", required = false) String realFileName, @RequestParam(value = "fileName", required = false) String fileName, HttpServletRequest request, HttpServletResponse response) throws CRMException { try { response.setCharacterEncoding("utf-8"); response.setContentType("multipart/form-data"); String rFName = URLEncoder.encode(realFileName, "UTF-8"); response.setHeader("Content-Disposition", "attachment;fileName=" + rFName); if (StringUtils.isEmpty(fileName) || fileName.contains("\\.\\.")) { response.setContentType("text/html;charset=utf-8"); response.getWriter().write("您下载的文件不存在!"); return null; } String filePath = request.getSession().getServletContext().getRealPath("../"); InputStream inputStream = new FileInputStream(new File(filePath + File.separator + fileName)); OutputStream os = response.getOutputStream(); byte[] b = new byte[1024]; int length; while ((length = inputStream.read(b)) > 0) { os.write(b, 0, length); } //日志记录 synergyProxy.downloadFile(realFileName,fileName,request); // 这里主要关闭。 os.flush(); os.close(); inputStream.close(); return null; } catch (Exception e) { e.printStackTrace(); } return null; } ====================================================================================================== /** * 文件对象 */ public class SynergyFiles implements Serializable { //附件名 private String name = null; //附件类型 private String type = null; //附件上传路径 private String path = null; //app连接地址 private String appPath = null; //附件大小 private String size = null; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public String getAppPath() { return appPath; } public void setAppPath(String appPath) { this.appPath = appPath; } } ================================================================================ //fileList传入 附件保存 String filesJson = (String) fileList; List<SynergyFiles> files = JSON.parseArray(filesJson, SynergyFiles.class); if (files != null && files.size() > 0) { for (int i = 0; i < files.size(); i++) { SynergyFiles sf = files.get(i); LOGGER.info("处理详情id{}上传名称为{},大小为{}附件,路径为{}!", synergyProcessId, sf.getName(), sf.getSize(), sf.getPath()); String fileType = sf.getType(); if(fileType.contains(".")) fileType = fileType.substring(1); fileAttachmentService.uploadAttachment(myId, (short) 0, synergyProcessId, sf.getName(), fileType, sf.getPath(), Integer.valueOf(sf.getSize())); } } else { LOGGER.info("处理详情id{}没有上传附件!", synergyProcessId); } =================================================================================
public class ImageZipUtil {
private File file = null; // 文件对象
private String inputDir; // 输入图路径
private String outputDir; // 输出图路径
private String inputFileName; // 输入图文件名
private String outputFileName; // 输出图文件名
private int outputWidth = 100; // 默认输出图片宽
private int outputHeight = 100; // 默认输出图片高
private boolean proportion = true; // 是否等比缩放标记(默认为等比缩放)
public ImageZipUtil() { // 初始化变量
inputDir = "";
outputDir = "";
inputFileName = "";
outputFileName = "";
outputWidth = 100;
outputHeight = 100;
}
public ImageZipUtil(File file) { // 初始化变量
this.file = file;
}
public void setInputDir(String inputDir) {
this.inputDir = inputDir;
}
public void setOutputDir(String outputDir) {
this.outputDir = outputDir;
}
public void setInputFileName(String inputFileName) {
this.inputFileName = inputFileName;
}
public void setOutputFileName(String outputFileName) {
this.outputFileName = outputFileName;
}
public void setOutputWidth(int outputWidth) {
this.outputWidth = outputWidth;
}
public void setOutputHeight(int outputHeight) {
this.outputHeight = outputHeight;
}
public void setWidthAndHeight(int width, int height) {
this.outputWidth = width;
this.outputHeight = height;
}
public void setFile(File file) {
this.file = file;
}
/*
* 获得图片大小
* 传入参数 String path :图片路径
*/
public long getPicSize(String path) {
file = new File(path);
return file.length();
}
// 图片处理
public String compressPic() {
try {
//获得源文件
if(file == null)
file = new File(inputDir + inputFileName);
if (!file.exists()) {
return "";
}
Image img = ImageIO.read(file);
// 判断图片格式是否正确
if (img.getWidth(null) == -1) {
System.out.println(" can't read,retry!" + "<BR>");
return "no";
} else {
int newWidth; int newHeight;
// 判断是否是等比缩放
if (this.proportion == true) {
// 为等比缩放计算输出的图片宽度及高度
double rate1 = ((double) img.getWidth(null)) / (double) outputWidth + 0.1;
double rate2 = ((double) img.getHeight(null)) / (double) outputHeight + 0.1;
// 根据缩放比率大的进行缩放控制
double rate = rate1 > rate2 ? rate1 : rate2;
newWidth = (int) (((double) img.getWidth(null)) / rate);
newHeight = (int) (((double) img.getHeight(null)) / rate);
} else {
newWidth = outputWidth; // 输出的图片宽度
newHeight = outputHeight; // 输出的图片高度
}
BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);
/*
* Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的
* 优先级比速度高 生成的图片质量比较好 但速度慢
*/
tag.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);
FileOutputStream out = new FileOutputStream(outputDir + outputFileName);
// JPEGImageEncoder可适用于其他图片类型的转换
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
return "ok";
}
public String compressPic (String inputDir, String outputDir, String inputFileName, String outputFileName) {
// 输入图路径
this.inputDir = inputDir;
// 输出图路径
this.outputDir = outputDir;
// 输入图文件名
this.inputFileName = inputFileName;
// 输出图文件名
this.outputFileName = outputFileName;
return compressPic();
}
public String compressPic(String inputDir, String outputDir, String inputFileName, String outputFileName, int width, int height, boolean gp) {
// 输入图路径
this.inputDir = inputDir;
// 输出图路径
this.outputDir = outputDir;
// 输入图文件名
this.inputFileName = inputFileName;
// 输出图文件名
this.outputFileName = outputFileName;
// 设置图片长宽
setWidthAndHeight(width, height);
// 是否是等比缩放 标记
this.proportion = gp;
return compressPic();
}
public String compressPic(File file, String outputDir, String outputFileName, int width, int height, boolean gp) {
this.file = file;
// 输出图路径
this.outputDir = outputDir;
// 输出图文件名
this.outputFileName = outputFileName;
// 设置图片长宽
setWidthAndHeight(width, height);
// 是否是等比缩放 标记
this.proportion = gp;
return compressPic();
}
// main测试
// compressPic(大图片路径,生成小图片路径,大图片文件名,生成小图片文名,生成小图片宽度,生成小图片高度,是否等比缩放(默认为true))
public static void main(String[] arg) {
ImageZipUtil mypic = new ImageZipUtil();
System.out.println("输入的图片大小:" + mypic.getPicSize("e:\\1.jpg") / 1024 + "KB");
int count = 0; // 记录全部图片压缩所用时间
for (int i = 0; i < 100; i++) {
int start = (int) System.currentTimeMillis(); // 开始时间
mypic.compressPic("e:\\", "e:\\test\\", "1.jpg", "r1"+i+".jpg", 120, 120, true);
int end = (int) System.currentTimeMillis(); // 结束时间
int re = end-start; // 但图片生成处理时间
count += re; System.out.println("第" + (i+1) + "张图片压缩处理使用了: " + re + "毫秒");
System.out.println("输出的图片大小:" + mypic.getPicSize("e:\\test\\r1"+i+".jpg")/1024 + "KB");
}
System.out.println("总共用了:" + count + "毫秒");
}
public static String getTimestampFileName(String fileName) {
long timestamp = System.currentTimeMillis();
String fileNameSuffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
return timestamp + fileNameSuffix;
}
}
================================================================================
前台使用uploadify
================================================================================
//添加界面的附件管理
$('#synergyFile').uploadify({
'swf': 'js/uploadify/uploadify.swf', //FLash文件路径
'buttonText': '选择附件', //按钮文本
'uploader': '**********************', //处理文件上传Action
'queueID': 'fileQueue', //队列的ID
'queueSizeLimit': 10, //队列最多可上传文件数量,默认为999
'auto': true, //选择文件后是否自动上传,默认为true
'multi': true, //是否为多选,默认为true
'removeCompleted': true, //是否完成后移除序列,默认为true
'fileSizeLimit': '10MB', //单个文件大小,0为无限制,可接受KB,MB,GB等单位的字符串值
'fileObjName': 'file',
'fileTypeDesc': 'Image Files', //文件描述
'fileTypeExts': '*.gif; *.jpg; *.png; *.bmp;*.tif;*.doc;*.docx;*.xls;*.xlsx;*.zip;*.pdf', //上传的文件后缀过滤器
'onUploadSuccess': function (file, data, response) {
if(response){
var html = $("#div_files").html();
var result = file.name + " ";
html = html + result;
$("#div_files").html(html);
var name_file = file.name;
var type_file = file.type;
var path_file = params.key.substr(params.key.indexOf('/'));
var size_file = file.size;
var afile = new SynergyFiles(name_file,path_file,type_file,size_file);
fileList.push(afile);
$.messager.alert('提示信息', file.name+'上传成功', 'info');
}else{
$.messager.alert('提示信息', file.name+'上传失败', 'info');
}
},
'onQueueComplete': function (event, data) { //所有队列完成后事件
// ShowUpFiles($("#Attachment_GUID").val(), "div_files"); //完成后更新已上传的文件列表
},
'onFallback': function () { //Flash无法加载错误
alert("您未安装FLASH控件,无法上传!请安装FLASH控件后再试。");
},
'onUploadStart': function (file) {
params = {};
var authHandle = new AuthHandler("http://statics.edianzu.cn/auth/upload");
params = authHandle.authPutDir(new Date().getMilliseconds()+file.type);
$("#synergyFile").uploadify("settings", 'formData', params); //动态传参数
},
'onUploadError': function (event, queueId, fileObj, errorObj) {
//alert(errorObj.type + ":" + errorObj.info);
}
});
/**
* SynergyFiles对象
*
* @param name
* @param path
* @param type
* @param size
*/
function SynergyFiles(name,path,type,size){
this.name=name;
this.path=path;
this.type=type;
this.size=size;
}
朱雀桥边野草花,乌衣巷口夕阳斜。
旧时王谢堂前燕,飞入寻常百姓家。
浙公网安备 33010602011771号