文件上传与下载

分手后的思念是犯贱 2024-02-17 22:50 136阅读 0赞

一)、文件上传(多文件,单文件)

(1)、上传单个文件:

jsp页面:

  1. <form action = "login.action" method = "post" enctype = "multipart/form-data">
  2. 账号:<input name = "name" type = "text"><br><br>
  3. 照片:<input name = "photo" type = "file"><br><br>
  4. <input type ="submit" value = "提交">

Action代码:

  1. package com.action;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import org.apache.commons.io.FileUtils;
  5. public class LoginAction {
  6. private String name ;
  7. private File photo;
  8. private String photoFileName;
  9. private String photoContentType;
  10. public String execute(){
  11. System.out.println(photoFileName);
  12. System.out.println(photoContentType);
  13. File destFile = new File("C:\\Users\\Administrator\\Pictures\\struts\\"+photoFileName);
  14. try {
  15. FileUtils.copyFile(photo, destFile);
  16. } catch (IOException e) {
  17. // TODO Auto-generated catch block
  18. e.printStackTrace();
  19. }
  20. return "success";
  21. }

到此为止简单的文件上传已经完成,但是,通常情况下文件不是保存在某个指定的盘下,而是保存在项目文件下,修改 如下:

  1. File destFile = new File(ServletActionContext.getServletContext().getRealPath("/upload/"+photoFileName));

(2)、上传多个文件:只需要将上例中的与文件相关的属性改成数组形式即可,然后将上传的方法,改为操作数组。

jsp代码:

  1. <form action = "login.action" method = "post" enctype = "multipart/form-data">
  2. 账号:<input name = "name" type = "text"><br><br>
  3. 照片:<input name = "photo" type = "file"><br><br>
  4. 照片:<input name = "photo" type = "file"><br><br>
  5. <input type ="submit" value = "提交">
  6. </form>

Action代码:

  1. import org.apache.struts2.ServletActionContext;
  2. public class LoginAction {
  3. private String name ;
  4. private File[] photo;
  5. private String[] photoFileName;
  6. private String[] photoContentType;
  7. public String execute(){
  8. // System.out.println(photoFileName);
  9. // System.out.println(photoContentType);
  10. // File destFile = new File("C:\\Users\\Administrator\\Pictures\\struts\\"+photoFileName);
  11. for (int i = 0; i < photo.length; i++) {
  12. try {
  13. File destFile = new File(ServletActionContext.getServletContext().getRealPath("/upload/"+photoFileName[i]));
  14. FileUtils.copyFile(photo[i], destFile);
  15. } catch (IOException e) {
  16. System.out.println("execute exception");
  17. }
  18. }
  19. return "success";
  20. }

(3)、限制文件名、类型、大小:

(1)、限制文件名:

  1. String filename = ServletActionContext.getServletContext().getRealPath("/upload/"
  2. +UUID.randomUUID().toString()
  3. +photoFileName.substring(photoFileName.lastIndexOf(".")));
  4. File destFile = new File(filename);
  5. FileUtils.copyFile(photo, destFile);

(2)、限制文件类型:(Action必须继承ActionSupport类!!!)

struts.xml文件配置:

  1. <package name = "default" namespace = "/" extends = "struts-default">
  2. <action name = "login" class = "com.action.LoginAction">
  3. <result name = "success">/ok.jsp</result>
  4. <result name = "input">/index.jsp</result>
  5. <interceptor-ref name="fileUpload">
  6. <param name="allowedTypes">
  7. image/png,image/gif,image/jpeg,image/jpg
  8. </param>
  9. </interceptor-ref>
  10. <interceptor-ref name="defaultStack"/>
  11. </action>
  12. </package>

自定义消息配置文件:massage.properties

  1. struts.messages.error.content.type.not.allowed=\u4E0A\u4F20\u6587\u6863\u7C7B\u578B\u4E0D\u6B63\u786E {1}

还需要在struts.xml中进行常量配置:

  1. <constant name="struts.custom.i18n.resources" value="massage"></constant>

(3)限制文件大小:

自定义消息配置:

  1. struts.messages.error.file.too.large=\u60A8\u4E0A\u4F20\u7684\u6587\u4EF6{1} \u8D85\u8FC7\u6700\u5927\u9650\u5236

struts.xml中添加:(大小自己定义)

  1. <param name="maximumSize">
  2. 1048576
  3. </param>

(二)、文件下载:

准备jsp页面

  1. <a href = "download.action">下载</a>

准备Aciton代码:

  1. package com.action;
  2. import java.io.InputStream;
  3. import org.apache.struts2.ServletActionContext;
  4. public class DownLoadAction {
  5. private String filename;
  6. private InputStream input;
  7. public String execute (){
  8. filename = "1.png";
  9. input = ServletActionContext.getServletContext().getResourceAsStream("/upload/"+filename);
  10. return "success";
  11. }

读取服务器端指定的文件,将此文件以输出流的方式响应给客户端。

Action的默认返回类型是“转发”,必须改成”流“的形式向客户端输出。

struts.xml文件配置:

  1. <action name = "download" class = "com.action.DownLoadAction">
  2. <result name = "success" type = "stream">
  3. <param name="inputName">input</param>
  4. <param name = "contentDisposition" >attachment;filename=${filename}</param>
  5. </result>
  6. </action>

文件名中午乱码问题

修改Action中的代码为:

  1. public String execute () throws Exception{
  2. filename = "呵呵.png";
  3. input = ServletActionContext.getServletContext().getResourceAsStream("/upload/"+filename);
  4. filename = URLEncoder.encode(filename,"utf-8");
  5. return "success";
  6. }

-——————————————————————-

设置文件名:

  1. /*
  2. * 创建文件名字
  3. */
  4. public String generateFileName(String fileName){
  5. String formateDate = new SimpleDateFormat("yyMMddHHmmss").format(new Date());
  6. int random = new Random().nextInt(10000);
  7. int position = fileName.lastIndexOf(".");
  8. String subStr = fileName.substring(position);
  9. return formateDate+random+subStr;
  10. }

-——————————————————————————————

文件上传:

  1. private File photo; //获取上传照片
  2. private String photoFileName; //获取上传照片名
  3. private String photoContentType; //获取上传照片类型
  4. /** 添加商品 */
  5. public String addMerchandise() {
  6. InputStream inputStream = null;
  7. OutputStream outputStream = null;
  8. /** 目标文件路径*/
  9. String dir = ServletActionContext.getServletContext().getRealPath("/Picture");
  10. /** 新文件名 */
  11. String newName = generateFileName(photoFileName);
  12. /** 目标文件 */
  13. File targetPhoto = new File(dir+"/"+newName);
  14. try {
  15. inputStream = new FileInputStream(photo);
  16. outputStream = new FileOutputStream(targetPhoto);
  17. byte[] bytes = new byte[1024];
  18. Integer r = 0;
  19. while(( r = inputStream.read(bytes,0,1024)) != -1 ) {
  20. outputStream.write(bytes, 0, r);
  21. }
  22. bookInfo.setPicture("/Picture/"+newName);
  23. bookInfo.setCategory(merchandiseService.loadCategory(category));
  24. merchandiseService.addMerchandise(bookInfo);
  25. return browseMerchandise();
  26. } catch (Exception e) {
  27. e.printStackTrace();
  28. }finally {
  29. try {
  30. if(inputStream != null) inputStream.close();
  31. if(outputStream != null) outputStream.close();
  32. } catch (IOException e) {
  33. e.printStackTrace();
  34. }
  35. }
  36. return "sorry";
  37. }
  38. /*
  39. * 创建文件名字
  40. */
  41. public String generateFileName(String fileName){
  42. String formateDate = new SimpleDateFormat("yyMMddHHmmss").format(new Date());
  43. int random = new Random().nextInt(10000);
  44. int position = fileName.lastIndexOf(".");
  45. String subStr = fileName.substring(position);
  46. return formateDate+random+subStr;
  47. }

发表评论

表情:
评论列表 (有 0 条评论,136人围观)

还没有评论,来说两句吧...

相关阅读

    相关 文件下载

    文件上传与下载 > 文件上传也称为upload,是指将本地图片、视频、音频等文件上传到服务器上,可以供其他用户浏览或下载的过程。文件上传在项目中应用非常广泛,我们经常发微

    相关 文件下载

    文件的上传与下载 文件的上传与下载在web应用中是非常常用,也是非常有用的。 例如:发送电子邮件时上传附件,下载网上资源时。 一、文件的上传 主要分为两个步骤:  

    相关 SFTP文件下载

    一、文件上传 说明1:所谓上传window上的文件上传到linux上 说明2:上传的文件会自动放到当前的用户的家目录 1:打开SFTP的窗口 Alt+p ![1297