controller.java
@SuppressWarnings("unchecked")
@RequestMapping("downloadFile")
public void downloadFile(String hightechId, String type, HttpServletRequest request, HttpServletResponse response) {
try {
// 根据高企信息id获取导出数据MAP
Map<String, Object> resultMap = this.hightechService.getHightechData(hightechId, type);
// 获取用户信息
Map<String, Object> viewCompany = (Map<String, Object>) resultMap.get("viewCompany");
// 获取申报年份
String mYear = MapUtils.getString(resultMap, "mYear");
// 获取企业名称
String companyName = MapUtils.getString(viewCompany, "companyName");
// 文件名称
String fileName = mYear + "年度" + companyName + "高新技术企业申报材料.pdf";
if ("0".equals(type)) {
//导出word
FreeMarkerTemplateUtil.downloadDoc(freemarkerConfigurer, "hightech.xml", resultMap, fileName.replace(".pdf", ".doc"), response);
} else {
// 临时文件个数
int fileInt = 1;
// 需要合并的附件路径
String fileUrl = "";
// 页面打印的方向
String direct = "0";
// 表中存放附件路径
String attachUrl = "";
// 图片服务器地址
String requestUrl = CustomizedPropertyConfigurer.getContextProperty("STATIC_SERVLET_URL");
// 临时数据列表
List<HightechAttachment> attachmentList = new ArrayList<HightechAttachment>();
// 存放文件路径前缀
// 根路径
String rootUrl = request.getServletContext().getRealPath("/");
// 目标文件路径
String masterUrl = rootUrl + "temp" + File.separator + super.getCompanyNameBiz(request) + File.separator;
// 中间文件路径
String slaveUrl = masterUrl + "slave" + File.separator;
// 创建文件目录
CCRDFile.createDir(slaveUrl);
PDFMergerUtility mergePdf = new PDFMergerUtility();
// 附件文件的合并
for (int i = 1; i < 17; i++) {
if (i == 5) continue;
direct = i== 2 ? "1" : "0";
fileUrl = slaveUrl + String.valueOf(fileInt++) + ".pdf";
FreeMarkerTemplateUtil.downloadPdf3(freemarkerConfigurer, "shightech" + String.valueOf(i) + ".ftl", direct,
resultMap, fileUrl, response, request);
mergePdf.addSource(fileUrl);
if (i == 8 || i == 11) {
fileUrl = slaveUrl + String.valueOf(fileInt++) + ".pdf";
FreeMarkerTemplateUtil.downloadPdf3(freemarkerConfigurer, "shightech-" + String.valueOf(i) + ".ftl", "1",
resultMap, fileUrl, response, request);
mergePdf.addSource(fileUrl);
}
if (i > 3) {
attachmentList = (List<HightechAttachment>) MapUtils.getObject(resultMap, "attachmentLists" + String.valueOf(i - 4));
for (HightechAttachment attachment : attachmentList) {
attachUrl = attachment.getAttachmentUrl();
if (RegexUtil.isPdf(attachUrl)) { // 附件为pdf格式时,直接追加到目标pdf中
fileUrl = masterUrl + attachUrl;
if (HttpClientUtil.httpRequestFileToLocal(requestUrl + attachUrl, fileUrl)) {
if (new File(fileUrl).exists()) {
mergePdf.addSource(fileUrl);
}
}
} else if (RegexUtil.isImage(attachUrl)) { // 附件为图片格式时,将图片转化为pdf,再将转化的pdf追加到目标pdf中
if (HttpClientUtil.httpRequestFileToLocal(requestUrl + attachUrl, masterUrl + attachUrl)) {
fileUrl = slaveUrl + String.valueOf(fileInt++) + ".pdf";
if (ImgPdfUtil.convertImgToPdf(masterUrl + attachUrl, fileUrl)) {
mergePdf.addSource(fileUrl);
}
}
}
}
}
}
// 合并后的文件
mergePdf.setDestinationFileName(masterUrl + fileName);
mergePdf.mergeDocuments();
// // pdf添加页码
// PDDocument doc = null;
// try {
// doc = PDDocument.load(masterUrl + fileName);
//
// List<?> allPages = doc.getDocumentCatalog().getAllPages();
// PDFont font = PDType1Font.HELVETICA;
// float fontSize = 12.0f;
// for (int i = 0; i < allPages.size(); i++) {
// PDPage page = (PDPage) allPages.get(i);
// PDPageContentStream footercontentStream = new PDPageContentStream(doc, page, true, true);
// footercontentStream.beginText();
// footercontentStream.setFont(font, fontSize);
// footercontentStream.setNonStrokingColor(Color.BLACK);
// footercontentStream.moveTextPositionByAmount((PDPage.PAGE_SIZE_A4.getUpperRightX() / 2),
// (PDPage.PAGE_SIZE_A4.getLowerLeftY() + 15));
// footercontentStream.drawString(String.valueOf(i + 1));
// footercontentStream.endText();
// footercontentStream.close();
// }
// doc.save(masterUrl + fileName);
// } finally {
// if (doc != null) {
// doc.close();
// }
// }
// 增加文档封面
PDFMergerUtility mergePdf2 = new PDFMergerUtility();
fileUrl = slaveUrl + String.valueOf(fileInt++) + ".pdf";
FreeMarkerTemplateUtil.downloadPdf3(freemarkerConfigurer, "shightech0.ftl", "0",
resultMap, fileUrl, response, request);
mergePdf2.addSource(fileUrl);
mergePdf2.addSource(masterUrl + fileName);
// 合并后的文件
mergePdf2.setDestinationFileName(masterUrl + fileName);
mergePdf2.mergeDocuments();
// 以流的形式下载文件
UploadImageUtil.downloadFile(masterUrl + fileName, response);
// 删除临时文件
CCRDFile.deleteFolder(masterUrl);
}
} catch (Exception e) {
e.printStackTrace();
}
}
FreeMarkerTemplateUtil.java
package com.mostchh.common.util;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
@Component
public class FreeMarkerTemplateUtil {
private static Configuration configuration = null;
static {
try {
configuration = new Configuration(Configuration.VERSION_2_3_23);
configuration.setDefaultEncoding("UTF-8");
//configuration.setTemplateUpdateDelayMilliseconds(0);
//configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
//cfg.setServletContextForTemplateLoading(getServletContext(), "/WEB-INF/templates");
configuration.setClassForTemplateLoading(FreeMarkerTemplateUtil.class, ""); // FTL文件所存在的位置
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 传入模板路径以及模板所需的数据,向页面输出HTML
*
* @param modelPath
* @param data
* @param response
*/
public static void preview(FreeMarkerConfigurer freemarkerConfigurer, String modelPath, Map<String, Object> data, HttpServletResponse response) {
try {
Template template = freemarkerConfigurer.getConfiguration().getTemplate(modelPath);
response.reset();
response.setHeader("content-type", "text/html;charset=utf-8");
PrintWriter writer = response.getWriter();
template.process(data, writer);
template.process(data, new PrintWriter(System.out));
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 传入模板数据,模板路径,给页面下载指定文件名的文件
*
* @param modelPath
* @param data
* @param response
* @param fileName
*/
public static void downloadDoc(FreeMarkerConfigurer freemarkerConfigurer, String modelPath, Map<String, Object> data,
String fileName, HttpServletResponse response) {
try {
Template template = freemarkerConfigurer.getConfiguration().getTemplate(modelPath);
response.reset();
response.setContentType("application/octet-stream;charset=utf-8");
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
PrintWriter writer = response.getWriter();
template.process(data, writer);
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 传入模板数据,模板路径,给页面下载指定文件名的文件(火狐下载文件名不乱码)
*
* @param modelPath
* @param data
* @param response
* @param fileName
* @param request
*/
public static void downloadDocNew(FreeMarkerConfigurer freemarkerConfigurer, String modelPath, Map<String, Object> data,
String fileName, HttpServletResponse response, HttpServletRequest request) {
try {
Template template = freemarkerConfigurer.getConfiguration().getTemplate(modelPath);
response.reset();
String agent = request.getHeader("USER-AGENT");
if(agent != null && agent.toLowerCase().indexOf("firefox") > 0){
fileName = "=?UTF-8?B?" + (new String(Base64Utils.encodeToString(fileName.getBytes("UTF-8")))) + "?=";
}else{
fileName = URLEncoder.encode(fileName, "utf-8");
}
response.setContentType("application/octet-stream;charset=utf-8");
//response.setHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(fileName, "utf-8"));
response.setHeader("content-disposition", "attachment;filename="+fileName);
PrintWriter writer = response.getWriter();
template.process(data, writer);
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 传入模板数据,模板路径,给页面下载指定文件名的文件
*
* @param modelPath
* @param data
* @param response
* @param fileUrl
*/
public static void downloadDoc2(FreeMarkerConfigurer freemarkerConfigurer, String modelPath, Map<String, Object> data,
String fileUrl, HttpServletResponse response) {
try {
Template template = freemarkerConfigurer.getConfiguration().getTemplate(modelPath);
File file = new File(fileUrl);
PrintWriter writer = new PrintWriter(file, "utf-8");
template.process(data, writer);
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param freemarkerConfigurer
* @param modelPath
* @param data
* @param response
* @param request
* @Title: downloadPdf
* @Description: 下载pdf
* @return: void
*/
public static void downloadPdf(FreeMarkerConfigurer freemarkerConfigurer, String modelPath, Map<String, Object> data,
String fileName, HttpServletResponse response, HttpServletRequest request) {
String htmlStr;
OutputStream os = null;
try {
htmlStr = FreeMarkerTemplateUtil.generate(freemarkerConfigurer, modelPath, data);
String appPath = request.getSession().getServletContext().getRealPath("/") + File.separator;
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(htmlStr, "file:" + appPath);
// 解决中文支持问题
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont(appPath + "/WEB-INF/template" + File.separator + "simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// 生成pdf文件
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
response.setContentType("application/pdf");
os = response.getOutputStream();
renderer.layout();
renderer.createPDF(os, true);
os.flush();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* @param freemarkerConfigurer
* @param modelPath
* @param data
* @param response
* @param request
* @Title: downloadPdf
* @Description: 下载pdf
* @return: String
*/
public static void downloadPdf2(FreeMarkerConfigurer freemarkerConfigurer, String modelPath, Map<String, Object> data,
String fileUrl, HttpServletResponse response, HttpServletRequest request) {
String htmlStr;
OutputStream os = null;
try {
htmlStr = FreeMarkerTemplateUtil.generate(freemarkerConfigurer, modelPath, data);
String appPath = request.getSession().getServletContext().getRealPath("/") + File.separator;
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(htmlStr, "file:" + appPath);
// 解决中文支持问题
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont(appPath + "/WEB-INF/template" + File.separator + "simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
os = new FileOutputStream(fileUrl);
renderer.layout();
renderer.createPDF(os, true);
os.flush();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* @param freemarkerConfigurer
* @param modelPath
* @param data
* @param response
* @param request
* @Title: downloadPdf
* @Description: 下载pdf
* @return: void
*/
@SuppressWarnings("deprecation")
public static void downloadPdf3(FreeMarkerConfigurer freemarkerConfigurer, String modelPath, String direct, Map<String, Object> data,
String fileUrl, HttpServletResponse response, HttpServletRequest request) {
OutputStream os = null;
try {
os = new FileOutputStream(fileUrl);
Configuration config = freemarkerConfigurer.getConfiguration();
config.setDefaultEncoding("UTF-8");
Template template = config.getTemplate(modelPath);
StringWriter result = new StringWriter();
template.setEncoding("UTF-8");
template.process(data, result);
result.flush();
String htmlData = result.toString();// 模版变量
Document document = new Document();
if ("1".equals(direct)) {
document.setPageSize(PageSize.A4.rotate());
}
PdfWriter writer = PdfWriter.getInstance(document, os);
// // 添加水印和页码
PDFBuilder builder = new PDFBuilder();
writer.setPageEvent(builder);
document.open();
// 根据不同系统设置不同字符集
String charset = System.getProperties().getProperty("os.name").toLowerCase().indexOf("linux") != -1 ? "utf-8" : "utf-8";
XMLWorkerHelper.getInstance().parseXHtml(writer, document, new ByteArrayInputStream(htmlData.getBytes("UTF-8")), Charset.forName(charset));
document.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* @param freemarkerConfigurer
* @param template
* @param params
* @return
* @throws Exception
* @Title: generate
* @Description: 生成html
* @return: String
*/
public static String generate(FreeMarkerConfigurer freemarkerConfigurer, String template, Map<String, Object> params) throws Exception {
Template tp = freemarkerConfigurer.getConfiguration().getTemplate(template);
StringWriter stringWriter = new StringWriter();
BufferedWriter writer = new BufferedWriter(stringWriter);
tp.process(params, writer);
String htmlStr = stringWriter.toString();
writer.flush();
writer.close();
return htmlStr;
}
/**
* Freemarker生成word
* 这个方法是固定的, 只是针对于'我的事项'模块的详情的导出
*
* @param request
* @param sysMessage 生成的实体类对象
* @param xmlTemplate
* @return
* @throws Exception
*/
public static byte[] createWordStream(HttpServletRequest request, Map<String, Object> sysMessage, String xmlTemplate) throws Exception {
Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
configuration.setDefaultEncoding("utf-8");
// 设置模板保存的路径
configuration.setServletContextForTemplateLoading(request.getSession().getServletContext(), "/common/template/my_message");
RichHtmlHandler handler = new RichHtmlHandler(sysMessage.get("content").toString(),"");
handler.setDocSrcLocationPrex("file:///C:/8597C935");//用到前面mht文件中的值
handler.setDocSrcParent("file7173.files");//用到前面mht文件中的值
handler.setNextPartId("01D48673.4CA379D0");//用到前面mht文件中的值
handler.setShapeidPrex("_x56fe__x7247__x0020");
handler.setSpidPrex("_x0000_i");
handler.setTypeid("#_x0000_t75");
handler.handledHtml(false);
String bodyBlock = handler.getHandledDocBodyBlock();
System.out.println("bodyBlock:\n"+bodyBlock);
String handledBase64Block = "";
if (handler.getDocBase64BlockResults() != null
&& handler.getDocBase64BlockResults().size() > 0) {
for (String item : handler.getDocBase64BlockResults()) {
handledBase64Block += item + "\n";
}
}
if(handledBase64Block==null){
handledBase64Block = "";
}
sysMessage.put("imagesBase64String", handledBase64Block);
String xmlimaHref = "";
if (handler.getXmlImgRefs() != null
&& handler.getXmlImgRefs().size() > 0) {
for (String item : handler.getXmlImgRefs()) {
xmlimaHref += item + "\n";
}
}
if(xmlimaHref==null){
xmlimaHref = "";
}
sysMessage.put("imagesXmlHrefString", xmlimaHref);
sysMessage.put("content", bodyBlock);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Writer w = new OutputStreamWriter(baos, StandardCharsets.UTF_8); // 设置输出流得编码格式, 避免导出乱码
// 获取模板
Template freemarkerTemplate = configuration.getTemplate(xmlTemplate);
// 写文件
freemarkerTemplate.process(sysMessage, w);
w.close();
return baos.toByteArray();
}
}
CustomizedPropertyConfigurer.java
public class CustomizedPropertyConfigurer extends PropertyPlaceholderConfigurer {
private static Map<String, Object> ctxPropertiesMap;
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props)
throws BeansException {
super.processProperties(beanFactory, props);
// load properties to ctxPropertiesMap
ctxPropertiesMap = new HashMap<String, Object>();
for (Object key : props.keySet()) {
String keyStr = key.toString();
String value = props.getProperty(keyStr);
ctxPropertiesMap.put(keyStr, value);
}
}
// static method for accessing context properties
public static String getContextProperty(String name) {
return ctxPropertiesMap.get(name).toString();
}
}
CCRDFile.java
public static boolean createDir(String destDirName) {
File dir = new File(destDirName);
if (dir.exists()) {// 判断目录是否存在
System.out.println("创建目录失败,目标目录已存在!");
return false;
}
if (!destDirName.endsWith(File.separator)) {// 结尾是否以"/"结束
destDirName = destDirName + File.separator;
}
if (dir.mkdirs()) {// 创建目标目录
System.out.println("创建目录成功!" + destDirName);
return true;
} else {
System.out.println("创建目录失败!");
return false;
}
}
UploadImageUtil.java
package com.mostchh.common.util;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Random;
/**
* 操作文件
*
* @author Administrator
*
*/
public class UploadImageUtil {
/**
* <p>
* 方法名
* </p>
* http接口图片上传
* @param requestUrl 请求地址
* @param filedata 上传文件流
* @param newName 新图片名称包括文件路径 如 /uploadfiles/adImg/a.jpg
* @return
*/
public static String httpPostImageRequest(String requestUrl, String newName, MultipartFile filedata) {
String end = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try {
URL url = new URL(requestUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
/* 允许Input、Output,不使用Cache */
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
/* 设置传送的method=POST */
con.setRequestMethod("POST");
/* setRequestProperty */
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
/* 设置DataOutputStream */
DataOutputStream ds = new DataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; " + "name=\"file1\";filename=\"" + newName + "\"" + end);
ds.writeBytes(end);
/* 取得文件的FileInputStream */
InputStream fStream = filedata.getInputStream();
filedata.getSize();
/* 设置每次写入1024bytes */
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
/* 从文件读取数据至缓冲区 */
while ((length = fStream.read(buffer)) != -1) {
/* 将资料写入DataOutputStream中 */
ds.write(buffer, 0, length);
}
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
/* close streams */
fStream.close();
ds.flush();
/* 取得Response内容 */
InputStream is = null;
try {
is = con.getInputStream();
} catch (IOException e) {
// e.printStackTrace();
is = con.getErrorStream();
}
int ch;
StringBuffer b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
/* 将Response显示于Dialog */
/* 关闭DataOutputStream */
ds.close();
return b.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* <p>
* 方法名
* </p>
* http接口图片上传
* @param requestUrl 请求地址
* @param filedata 上传文件流
* @param newName 新图片名称包括文件路径 如 /uploadfiles/adImg/a.jpg
* @return
*/
public static String httpPostImageRequest(String requestUrl, String newName, MultipartFile filedata,String sessionId) {
String end = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try {
URL url = new URL(requestUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
/* 允许Input、Output,不使用Cache */
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
/* 设置传送的method=POST */
con.setRequestMethod("POST");
/* setRequestProperty */
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
/* 设置DataOutputStream */
DataOutputStream ds = new DataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; " + "name=\"file1\";filename=\"" + newName + "\"" + end);
ds.writeBytes(end);
/* 取得文件的FileInputStream */
InputStream fStream = filedata.getInputStream();
//使用sessionid + 文件名生成文件号
String id = sessionId + filedata.getOriginalFilename();
//向单例哈希表写入文件长度和初始进度
ProgressSingleton.put(id + "Size",filedata.getSize());
//文件进度长度
long progress = 0;
/* 设置每次写入1024bytes */
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
/* 从文件读取数据至缓冲区 */
while ((length = fStream.read(buffer)) != -1) {
/* 将资料写入DataOutputStream中 */
ds.write(buffer, 0, length);
//每读取一次,更新一次进度大小
progress = progress + length;
//向单例哈希表写入进度
ProgressSingleton.put(id + "Progress", progress);
System.out.println("------Progress---:"+ProgressSingleton.get(id + "Progress"));
}
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
/* close streams */
fStream.close();
ds.flush();
//当文件上传完成之后,从单例中移除此次上传的状态信息
ProgressSingleton.remove(id + "Size");
ProgressSingleton.remove(id + "Progress");
/* 取得Response内容 */
InputStream is = con.getInputStream();
int ch;
StringBuffer b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
/* 将Response显示于Dialog */
/* 关闭DataOutputStream */
ds.close();
return b.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
*
* 功能描述 保存图片
*
* @author :
*
* @param filedata
* 文件数据
* @param pathPrefix
* 文件保存路径前缀
* @throws IOException
* @throws IllegalStateException
*
*
*/
public static String saveFile(String pathPrefix, MultipartFile filedata,String sessionId) throws IllegalStateException, IOException {
// 获取图片的文件名
String fileName = filedata.getOriginalFilename();
// 获取图片的扩展名
String extensionName = fileName.substring(fileName.lastIndexOf(".") + 1);
// 获取随机4位数
String randomNum = String.valueOf(new Random().nextInt(9000) + 1000);
// 新的图片文件名 = 获取时间戳+"."图片扩展名
String newFileName = String.valueOf(System.currentTimeMillis() + randomNum) + "." + extensionName;
// 图片保存请求路径
String requestUrl = CustomizedPropertyConfigurer.getContextProperty("STATIC_SERVLET_URL") + "/staticServlet";
// 上传图片的相对路径
String filePath = CustomizedPropertyConfigurer.getContextProperty("FILE_UPLOAD_FILES") + pathPrefix + "/" +
DateUtils.getYear() + "/" + DateUtils.getMonth() + "/" + newFileName;
// 上传图片
httpPostImageRequest(requestUrl, filePath, filedata,sessionId);
return filePath;
}
/**
*
* 功能描述 保存图片
*
* @author :
*
* @param filedata
* 文件数据
* @param pathPrefix
* 文件保存路径前缀
* @throws IOException
* @throws IllegalStateException
*
*
*/
public static String saveFile(String pathPrefix, MultipartFile filedata) throws IllegalStateException, IOException {
// 获取图片的文件名
String fileName = filedata.getOriginalFilename();
// 获取图片的扩展名
String extensionName = fileName.substring(fileName.lastIndexOf(".") + 1);
// 获取随机4位数
String randomNum = String.valueOf(new Random().nextInt(9000) + 1000);
// 新的图片文件名 = 获取时间戳+"."图片扩展名
String newFileName = String.valueOf(System.currentTimeMillis() + randomNum) + "." + extensionName;
// 图片保存请求路径
String requestUrl = CustomizedPropertyConfigurer.getContextProperty("STATIC_SERVLET_URL") + "/staticServlet";
// 上传图片的相对路径
String filePath = CustomizedPropertyConfigurer.getContextProperty("FILE_UPLOAD_FILES") + pathPrefix + "/" +
DateUtils.getYear() + "/" + DateUtils.getMonth() + "/" + newFileName;
// 上传图片
httpPostImageRequest(requestUrl, filePath, filedata);
return filePath;
}
/**
*
* <p>
* 方法名
* </p>
* 获取文件扩展名
*
* @param fileName
* @return
*/
@SuppressWarnings("unused")
private static String getExtention(String fileName) {
int pos = fileName.lastIndexOf(".");
return fileName.substring(pos);
}
/**
* 删除图片
*
* @param deletePath 删除图片的路径
* @return
*/
public static void deleteImage(String deletePath) {
// 图片删除请求路径
String requestUrl = CustomizedPropertyConfigurer.getContextProperty("STATIC_SERVLET_URL") + "/delStaticServlet";
// 删除图片的相对路径
if (deletePath.indexOf("uploadfiles") != -1) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("filePath=").append(deletePath);
HttpClientUtil.httpRequest(requestUrl, stringBuffer.toString());
}
}
/**
* 已流的形式下载文件
* @param path
* @param response
* @return
*/
public static HttpServletResponse downloadFile(String path, HttpServletResponse response) {
try {
// path是指欲下载的文件的路径。
File file = new File(path);
// 取得文件名。
String filename = file.getName();
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return response;
}
}