本地上传文件到服务器,从服务器下载文件到本地
最近在做项目的时候涉及到了文件的上传、下载,以前学习IO时也没有搞得多清楚,在网上找了些上传下载的例子,然后修改了部分。经测试,上传下载文件暂时能用,下面是上传和下载的方法:
1.本地上传文件到服务器
html代码:
<form id="uploadDatumInfo" name="uploadDatumInfo" method="post" enctype="multipart/form-data" target="target_upload"><!-- 注意要加上:enctype="multipart/form-data"--> <input type="file" id="datum_address" name="datum_address" class="" /> </form>
js代码:
function uploadDatum() {
<!-- 验证上传文件是否为空 --> var datum_address=$("#datum_address").val(); if(datum_address=='') { alert("上传文件不能为空!"); return; } <!-- 提交表单数据 --> document.uploadDatumInfo.action="<%=WebConstants.WEB_ROOT%>/saveUploadMyDatum.do?&<%=MctsUtils.getURLRandom() %>"; document.uploadDatumInfo.submit(); }
后台代码:@Controller
@Controller
public class MyController { @Resource(name = "MyService") private MyService myService; private ResourceManager rm = ResourceManager.getInstance(); //保存上传资料信息 @RequestMapping(value = "/saveUploadMyDatum.do") public void saveUploadMyDatum(HttpServletRequest request, HttpServletResponse response, final ModelMap context, VcDatumInfo vcDatumInfo) throws Exception { try { String myDir = rm.getValue("my_file_path"); String fileDir = rm.getValue("my_space_path"); File sourceFolder = new File(myDir + "/" + fileDir);创建存储文件夹 if (!sourceFolder.exists())
{ sourceFolder.mkdirs(); } String datum_address = ""; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(2048 * 1024); UploadProgressListener getBarListener = new UploadProgressListener(request); ServletFileUpload upload = new ServletFileUpload(factory); upload.setProgressListener(getBarListener); List<Object> formList = upload.parseRequest(request); Iterator<Object> formItem = formList.iterator(); while (formItem.hasNext())
{ FileItem item = (FileItem) formItem.next(); if (!item.isFormField())
{ if (item != null && item.getSize() > 0)
{ String fieldName = item.getFieldName(); String timeTemp = String.valueOf(new Date().getTime()); String subname = item.getName().substring( item.getName().lastIndexOf(".", item.getName().length()));//获取上传文件的后缀名 String realName = item.getName().substring(0, item.getName().lastIndexOf("."));//获取上传文件的文件名 //System.out.println(realName); if (fieldName.equals("datum_address"))
{ datum_address = fileDir + "/" + "datum_" + timeTemp + "_" + realName + subname;//要保存到数据库中的文件地址
File file = new File(myDir + "/" + datum_address);//创建保存路径
item.write(file);//写入文件数据
}
}
}
}
}
}
}
2.从服务器下载文件
后台代码:
String myDir = rm.getValue("my_file_path"); OutputStream toClient = null; String path = ""; path = myDir + "/" + vcDatumInfo.getDatum_address(); try { // path是指欲下载的文件的路径。 File file = new File(path); // 取得文件名 String filename = file.getName(); // 取得文件的后缀名。 String ext = filename.substring(filename.lastIndexOf(".") + 1); String realName = file.getName().substring(file.getName().lastIndexOf("_") + 1, file.getName().lastIndexOf("."));//取得文件名,这一步得到的文件名有可能不是上传时的原文件名 String realFileName = realName + "." + ext; // 以流的形式下载文件 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=" + java.net.URLEncoder.encode(realFileName, "UTF-8"));//注意这一步设置文件名时,中文容易出现乱码 response.addHeader("Content-Length", "" + file.length()); toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); toClient.write(buffer); vcDatumInfo.setDownload_number(vcDatumInfo.getDownload_number() + 1); vcSpaceService.updateDatumInfo(vcDatumInfo); } catch (IOException ex) { ex.printStackTrace(); }finally { if(toClient != null) { toClient.flush(); toClient.close(); } }
最后,感谢分享例子的作者!
本文出自wentaokyle,转载请标明出处!谢谢!