2007-07-02
struts 中实现文件的上传
------------文件上传
java 代码
- public class UploadFile {
- public static String upLoad(FormFile file,String uploadDir,String newName) throws FileNotFoundException, IOException{
- String data = null;
- String location = null;
- String totalname;
- String extend;
- StringBuffer fileName;
- String contentType;
- String size;
- int i;
- File dirPath;
- InputStream inputStream;
- OutputStream outputStream;
- //得到上传文件的全名,包括扩展名
- totalname = file.getFileName();
- //得到扩展名
- i = totalname.lastIndexOf(".");
- //如果没有上传图片,则返回空
- if(i==-1){
- return location;
- }
- extend = totalname.substring(i);
- //重命名该文件
- fileName = new StringBuffer(newName + extend);
- fileName.toString();
- //得到文件类型
- contentType = file.getContentType();
- //得到文件大小
- size = (file.getFileSize() + " bytes");
- dirPath = new File(uploadDir);
- if (!dirPath.exists()) {
- dirPath.mkdirs();
- }
- inputStream = file.getInputStream();
- outputStream = new FileOutputStream(uploadDir + fileName);
- int bytesRead = 0;
- byte[] buffer = new byte[8192];
- while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
- outputStream.write(buffer, 0, bytesRead);
- }
- location = dirPath.getAbsolutePath()
- + System.getProperty("file.separator") + fileName + "\"";
- outputStream.close();
- inputStream.close();
- file.destroy();
- return location;
- }
- }
--------------------文件的下载
java 代码
- public ActionForward execute(ActionMapping mapping, ActionForm form,
- HttpServletRequest request, HttpServletResponse response) {
- String strFileName = "测试文件.rar";
- File file = new File("具体路径" + strFileName);//
- if(file.exists()){
- try{
- BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
- byte[] buffer = new byte[1024];
- strFileName = java.net.URLEncoder.encode(strFileName, "UTF-8");//处理中文文件名的问题
- strFileName = new String(strFileName.getBytes("UTF-8"),"GBK");//处理中文文件名的问题
- response.reset();
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application/x-rar-compressed");//不同类型的文件对应不同的MIME类型
- response.setHeader("Content-Disposition","attachment; filename=" + strFileName);
- OutputStream os = response.getOutputStream();
- while(bis.read(buffer) > 0){
- os.write(buffer);
- }
- bis.close();
- os.close();
- }
- catch(Exception e){
- ......
- }
- }
- return mapping.getInputForward();
- }
- 12:41
- 浏览 (338)
- 评论 (0)
- 分类: struts-webwork
- 相关推荐
发表评论
- 浏览: 15182 次
- 性别:

- 来自: 湖南长沙

- 详细资料
搜索本博客
最近加入圈子
最新评论
-
JAVA反射机制的学习
那 反射后带来的 调试困难呢
-- by tieshow -
JAVA反射机制的学习
什么时候能直接eval()就好了,不过新的语言规范加入了脚本支持。
-- by runthu -
JAVA反射机制的学习
感谢ing!对于反射的理解,最好还是自己动手code一下。像spring这些框架 ...
-- by tibetjungle -
JAVA反射机制的学习
反射机制可以简化有规律的代码,也可以增加程序的灵活性。 比如struts Act ...
-- by sunsong -
JAVA反射机制的学习
liang.zeng 写道java 的反射机制是很费资源的,程序中还是少用。 ...
-- by icewubin






评论排行榜