上传:
jsp:
<form:form commandName="uploadForm" method="post" action="${ctx}/purcorder/upload.do" enctype="multipart/form-data" ><div class="div0">
<input type="hidden" value="${p.pkPoid }" name="pkPoid">
</div>
<div> <span class="font4">Locate the file then click upload.</span><input type="file" name="uploadFile"/></div>
<div class="savebutton"><input type="submit" value="Save and Proceed"/></div>
</div>
</div>
</form:form>
controler:
@RequestMapping(value = "/upload.do", method = RequestMethod.POST)
public String upload(@RequestParam("uploadFile") MultipartFile multipartFile, @ModelAttribute("uploadForm") Object uploadForm, BindingResult errors,HttpServletRequest request, ModelMap model) {
logger.debug("uploading file...{}", request);
String pkPoid = request.getParameter("pkPoid");
final String filePath = "/fileupload.properties";
try {
FileHandlerFactory handler = FileHandlerFactory.getInstance(filePath, request);
//transfer file to disk.
final String storePath = handler.getFileConfig().getProperty("com.pccw.oframework.utility.upload.persistenceFolder");
String dbFileName = multipartFile.getOriginalFilename()+(new Date()).getTime();
File dest = new File(storePath+"/"+ dbFileName);
logger.info("transfering file to {}", dest.getAbsolutePath());
multipartFile.transferTo(dest);
//invoke handler to process file.
ValidationResult result = handler.handleFile(dest);
Set<Map.Entry<String,String>> ferrs= result.getErrors().entrySet();
for(Entry<String,String> entry: ferrs){
errors.reject(entry.getKey(), entry.getValue());
}
//add file handler error to request.
model.addAttribute("fileErrorsMap", handler.getFileErrorsMap());
//获得上传的所有文件
List<PDTO> pLDTO = pService.getFileInforByPoId(pkPoid);
model.addAttribute("pLDTO", pLDTO);
} catch (Exception e1) {
logger.error("Error in intiating File Handler.", e1);
errors.reject("", "Error in intiating File Handler.");
}
return "redirect:/purc/view/"+pkPoid+".do";
}
--------------------------------------------------------------------------------------------------------------------------------------
下载:
jsp:
<c:forEach var="o" items="${pLDTO}">
<div class="trow">
<div class="c c1"><a href="${ctx}/purcorder/download/${o.pouploads.pkPouploadId}.do">${o.pouploads.fileName}</a></div>
<button>Edit</button>
</div>
<div class="c cclear"></div>
</div>
</c:forEach>
control:
@RequestMapping("/download/{pkPouploadId}.do")
public String download(ModelMap model, HttpServletRequest request,
HttpServletResponse response,@PathVariable("pkPouploadId") String pkPouploadId) {
Pouploads Pouploads = pouploaderService.getPouploadsById(pkPouploadId);
// 输出的应用类型
response.setCharacterEncoding("UTF-8");
// filenames是自定义的文件名
String fileName = Pouploads.getFileName();
final String filePath = "/fileupload.properties";
FileHandlerFactory handler = null;
try {
handler = FileHandlerFactory.getInstance(filePath, request);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
final String storePath = handler.getFileConfig().getProperty("com.pccw.oframework.utility.upload.persistenceFolder");
File file = new File(storePath+"/"+ dbFileName);
/*try {
fileName = new String(file.getName().getBytes("GBK"),"iso8859-1");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}*/
response.setHeader("Content-Disposition", "attachment;filename="
+ fileName);
response.setContentType("application/octet-stream");
InputStream is = null;
OutputStream out = null;
try {
is = new FileInputStream(file);
out = response.getOutputStream();
for (int c = is.read(); c != -1; c = is.read()) {
out.write(c);
}
is.close();
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}finally{
close(is,out);
}
return null;
}
/**
* @Description:关闭IO流
*/
private void close(InputStream is, OutputStream out) {
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
-----------------------------------------------------------------------------------------------------------------------------------
下载2
HTML:
<td><input type="button" value="下载模版" class="export" οnclick="downloadTemplate();"/></td>
js:
//下载excel模板
function downloadTemplate(){
//下载模版的action地址
var url = "<%=request.getContextPath()%>/importAndExport.do?method=down";
var form=document.getElementById("archExampleForm");
form.setAttribute("action",url);
form.submit();
}
action:
/**
* @Description:下载模版
*/
public void down(ActionMapping mapping, ActionForm baseForm, HttpServletRequest request, HttpServletResponse response) throws Exception{
String excelTemplatPath = request.getParameter("excelTemplatPath");
// 服务器端源文件路径
String realPath = request.getRealPath("")+"//WEB-INF//template//xls//"+excelTemplatPath;
String excelTemplatFileName = request.getParameter("excelTemplatFileName");
System.out.println("excelTemplatFileName-----------------------------"+excelTemplatFileName);
// 文件名
String fileName =excelTemplatFileName+"(数据导入模板).xls";
ImportExternalDataToDB.downloadFile(response, fileName, realPath);
}
下载类:
public static void downloadFile( HttpServletResponse response,String fileName,String realPath){
try{
response.setContentType("application/x-msdownload");
// 设置下载框文件名显示内容及编码
response.addHeader("Content-Disposition","attachment; filename=\"" + java.net.URLEncoder.encode(fileName,"UTF-8") + "\"");
ServletOutputStream out = response.getOutputStream();
InputStream input = new FileInputStream(new File(realPath));
byte[] b = new byte[4096];
int len;
while ((len = input.read(b)) > 0) {
out.write(b, 0, len);
}
input.close();
out.flush();
out.close();
}catch (Exception e) {
e.printStackTrace();
}
}