jsp页面上传图片文件到服务器页面无刷新的技巧

时间:2022-05-05 13:02:45
        最近做SSH项目碰到一个问题,我在页面上想上传一个图片文件到服务器,但是在上传前希望能在页面上看到图片的预览。查了一下资料,发现有几种方式可以完成这个功能。一种是通过javascript来实现这个预览的功能,但是这种方法对浏览器有限制,有的浏览器用此方法无效。一种是通过ajax实现,还有一种就是通过无刷新页面上传文件到服务器,通过显示服务器上的临时图片文件也可以实现预览的效果。

        下面讲的就是最后一种方式。先看页面文件test.html源码:

<!DOCTYPE html>
<html>
  <head>
    <title>test.html</title>
	
    <meta name="keywords" content="keyword1,keyword2,keyword3">
    <meta name="description" content="this is my page">
    <meta name="content-type" content="text/html; charset=GB18030">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

<script type="text/javascript">
function callback(msg)   
{   
    document.getElementById("file").outerHTML = document.getElementById("file").outerHTML;   
    document.getElementById("msg").innerHTML = "<font color=red>"+msg+"</font>";   
}   
</script>
  </head>
  
  <body>
    <form action="/ECSystem/imgupload" id="form1" name="form1" encType="multipart/form-data"  method="post" target="hidden_frame">
      
    <input type="file" id="file" name="file" style="width:450" accept=".jpg, .gif">   
    <INPUT type="submit" value="上传文件"><span id="msg"></span>   
    <br>   
    <font color="red">支持JPG,JPEG,GIF,BMP,SWF,RMVB,RM,AVI文件的上传</font>               
    <iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe>
</form>
  
  </body>
</html>


        上面的源码中,要上传图片文件form的属性里必须有 encType= "multipart/form-data"  method= "post"z,想要页面不刷新,“ target= "hidden_frame"这个是必要的设置,表示页面的action请求刷新到iframe里,不必刷新整个页面。


        

        struts.xml文件为设置为:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">  
        <action name="imgupload" class="com.struts.action.ImageUploadAction">
        </action>
    </package>
</struts>


        Action的代码实现ImageUploadAction.java内容:

package com.struts.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;

import org.apache.struts2.ServletActionContext;



public class ImageUploadAction {
	private String fileFileName;
	private File file;
	private static final int BUFFER_SIZE = 64 * 1024 ; //缓冲器大小
	private String imageFileName;
	
	public void setFile(File file) {   
        this.file = file;   
    }
	
	public void setFileFileName(String fileFileName) {   
        this.fileFileName = fileFileName;   
    }
	
	public int getFileSizes(File f) throws Exception {//取得文件大小
	       int s = 0;
	       if (f.exists()) {
	           FileInputStream fis = null;
	           fis = new FileInputStream(f);
	           s= fis.available();
	           if (fis != null)
	        	   fis.close();
	       }
	       return s;
	}
	
	private void copy(File src, File dst) throws Exception {
		if (!src.exists())
			return;
		PrintWriter document_out = ServletActionContext.getResponse().getWriter();
		Boolean result = true;
		int filesize = getFileSizes(src);
		try {
			InputStream in = null ;
			OutputStream out = null ;
			try { 
				in = new BufferedInputStream( new FileInputStream(src), BUFFER_SIZE);
				out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
				byte [] buffer = new byte [BUFFER_SIZE];
				while (in.read(buffer, 0, filesize) > 0 ) {
					out.write(buffer, 0, filesize);
				}
			} finally {
				if ( null != in) {
					in.close();
				} 
				if ( null != out) {
					out.close();
				} 
			} 
		} catch (Exception e) {
			result = false;
			e.printStackTrace();
		} 
		if (result == true) {
			document_out.print("<script>parent.callback('upload file success');</script>");
		}
		else {
			document_out.print("<script>parent.callback('upload file fail');</script>");
		}
	} 
	
	private static String getExtention(String fileName) {
		int pos = fileName.lastIndexOf( "." );
		return fileName.substring(pos);
	} 

	
	public String execute() throws Exception {
		
		imageFileName = new Date().getTime() + getExtention(this.fileFileName);
		File imageFile = new File(ServletActionContext.getServletContext().getRealPath("/") + imageFileName);
		copy(file, imageFile);
		
		return "success";
	}

}

这样就ok了