'/>创建一个Actionpackagetutorial;importjava.io.BufferedInputStream;importjava.io.Buffer" />

Struts2图片上传并显示

Struts2图片上传并显示
Struts2图片上传并显示

Struts2图片上传并显示

首先创建项目并导入Struts的支持

上传页面Index.jsp

显示图片的页面ShowUpload.jsp

style="padding: 3px; border: solid 1px #cccccc; text-align: center">


创建一个Action

package tutorial;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import https://www.360docs.net/doc/0215743762.html,.URL;

import java.util.Date;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("unused")

public class FileUploadAction extends ActionSupport { private static final long serialVersionUID = 572146812454l;

private static final int BUFFER_SIZE = 16 * 1024;

private File myFile;

private String contentType;

private String fileName;

private String imageFileName;

private String caption;

//省略了get和set方法……

private static void copy(File src, File dst) {

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) {

out.write(buffer);

}

} finally {

if (null != in) {

in.close();

}

}

if (null != out) {

out.close();

}

} catch (Exception e) {

e.printStackTrace();

}

}

private static String getExtention(String fileName) { int pos = https://www.360docs.net/doc/0215743762.html,stIndexOf(".");

return fileName.substring(pos);

}

@Override

public String execute() {

imageFileName = new Date().getTime() + getExtention(fileName);

File imageFile = new File(ServletActionContext.getServletContext()

.getRealPath("/UploadImages")

+ "/" + imageFileName);

copy(myFile, imageFile);

return SUCCESS;

}

}

注意:要在WebRoot下创建一个文件夹UploadImages用于存放图片,但上传的图片只在服务器上能看到,页面前端也可以显示出来

Struts.xml的配置

/ShowUpload.jsp

相关主题
相关文档
最新文档