文件上传与下载

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

(1)、上传单个文件:

jsp页面:

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

Action代码:

package com.action;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class LoginAction {
    private String name ;
    private File photo;
    private String photoFileName;
    private String photoContentType;
    
    public String execute(){
    	System.out.println(photoFileName);
    	System.out.println(photoContentType);
    	File destFile = new File("C:\\Users\\Administrator\\Pictures\\struts\\"+photoFileName);
    	try {
			FileUtils.copyFile(photo, destFile);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return "success";
    }
到此为止简单的文件上传已经完成,但是,通常情况下文件不是保存在某个指定的盘下,而是保存在项目文件下,修改 如下:
 	File destFile = new File(ServletActionContext.getServletContext().getRealPath("/upload/"+photoFileName));

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

jsp代码:

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

Action代码:

import org.apache.struts2.ServletActionContext;

public class LoginAction {
    private String name ;
    private File[] photo;
    private String[] photoFileName;
    private String[] photoContentType;
    
    public String execute(){
//    	System.out.println(photoFileName);
//    	System.out.println(photoContentType);
//    	File destFile = new File("C:\\Users\\Administrator\\Pictures\\struts\\"+photoFileName);
    	for (int i = 0; i < photo.length; i++) {
        	try {
        	 	File destFile = new File(ServletActionContext.getServletContext().getRealPath("/upload/"+photoFileName[i]));
    			FileUtils.copyFile(photo[i], destFile);
    		} catch (IOException e) {
    			System.out.println("execute exception");
    		}			
		}
    	return "success";
    }

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

(1)、限制文件名:

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

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

struts.xml文件配置:

    <package name = "default" namespace = "/" extends = "struts-default">
       <action name = "login" class = "com.action.LoginAction">
          <result name = "success">/ok.jsp</result>
          <result name = "input">/index.jsp</result>
          
          <interceptor-ref name="fileUpload">
             <param name="allowedTypes">
                 image/png,image/gif,image/jpeg,image/jpg
             </param>
          </interceptor-ref>
          <interceptor-ref name="defaultStack"/>
       </action>
    </package>

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

struts.messages.error.content.type.not.allowed=\u4E0A\u4F20\u6587\u6863\u7C7B\u578B\u4E0D\u6B63\u786E {1}
还需要在struts.xml中进行常量配置:

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


(3)限制文件大小:

自定义消息配置:

struts.messages.error.file.too.large=\u60A8\u4E0A\u4F20\u7684\u6587\u4EF6{1} \u8D85\u8FC7\u6700\u5927\u9650\u5236
struts.xml中添加:(大小自己定义)

             <param name="maximumSize">
                1048576
             </param>


(二)、文件下载:

准备jsp页面

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

准备Aciton代码:

package com.action;

import java.io.InputStream;

import org.apache.struts2.ServletActionContext;

public class DownLoadAction {
   private String filename;
   private InputStream input;
   
   public String execute (){
	   filename = "1.png";
	  input =  ServletActionContext.getServletContext().getResourceAsStream("/upload/"+filename);
	   return "success";
   }

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

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

struts.xml文件配置:

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

文件名中午乱码问题

修改Action中的代码为:

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

----------------------------------------------

设置文件名:

	/*
	 * 创建文件名字
	 */
	public String generateFileName(String fileName){
		String formateDate = new SimpleDateFormat("yyMMddHHmmss").format(new Date());
		int random = new Random().nextInt(10000);
		int position = fileName.lastIndexOf(".");
		String subStr = fileName.substring(position);
		return formateDate+random+subStr;
	}

-------------------------------------------------------------

文件上传:

	private File photo;  //获取上传照片
	private String photoFileName;  //获取上传照片名
	private String photoContentType;  //获取上传照片类型

	/** 添加商品 */
	public String addMerchandise() {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		/** 目标文件路径*/
		String dir = ServletActionContext.getServletContext().getRealPath("/Picture");
		/** 新文件名 */
		String newName = generateFileName(photoFileName);
		/** 目标文件 */
		File targetPhoto = new File(dir+"/"+newName);
		
		try {
			inputStream = new FileInputStream(photo);
			outputStream = new FileOutputStream(targetPhoto);
			byte[] bytes = new byte[1024];
			Integer r = 0;
			while(( r = inputStream.read(bytes,0,1024)) != -1 ) {
				outputStream.write(bytes, 0, r);
			}
			
			bookInfo.setPicture("/Picture/"+newName);
			bookInfo.setCategory(merchandiseService.loadCategory(category));
			merchandiseService.addMerchandise(bookInfo);
			return browseMerchandise();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
				try {
					if(inputStream != null) inputStream.close();
					if(outputStream != null) outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			
		}
		return "sorry";
	} 
	/*
	 * 创建文件名字
	 */
	public String generateFileName(String fileName){
		String formateDate = new SimpleDateFormat("yyMMddHHmmss").format(new Date());
		int random = new Random().nextInt(10000);
		int position = fileName.lastIndexOf(".");
		String subStr = fileName.substring(position);
		return formateDate+random+subStr;
	}	





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柏油

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值