您的位置首页生活百科

jquery.fileupload使用例子java

jquery.fileupload使用例子java

的有关信息介绍如下:

jquery.fileupload使用例子java

开发的时候需要使用jquery.fileupload插件,那么如何在struts中使用呢

需要的css样式和js文件

jsp页面信息如下,整个页面信息

<%@ page language="java" contentType="text/html; charset=utf-8"

pageEncoding="utf-8" import="java.io.*"%>

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme() + "://"

+ request.getServerName() + ":" + request.getServerPort()

+ path + "/";

%>

content="initial-scale=1.0,user-scalable=no, minimum-scale=1,maximum-scale=1,width=device-width"

name="viewport">

上传图片

文件上传

id="fileupload" type="file" name="file" multiple>

这里特别注意文件名称,容易出错的地方

后台处理上传图片的方法,使用的是struts2处理

对应前端的文件名name="file"

struts2已经处理了请求,我们之间用就可以了

public String saveattach() {

try {

BufferedImage bi = ImageIO.read(file);

if (bi == null) {

return "0";

}

} catch (IOException e) {

return "0";

}

String realpath = ServletActionContext.getServletContext().getRealPath("/images/");

if (!new File(realpath).exists()) {

new File(realpath).mkdir();

}

String[] typechoose = fileFileName.split("\\.");

int ichoose = typechoose.length;

String type = ichoose > 1 ? typechoose[ichoose - 1] : "";

if (type.toLowerCase().equals("jpg")

|| type.toLowerCase().equals("gif")

|| type.toLowerCase().equals("jpeg")

|| type.toLowerCase().equals("png")) {

SimpleDateFormat smat = new SimpleDateFormat("yyyyMMddHHmmss");

String newfilname = smat.format(new Date()) + "." + type;

String path = realpath + "/" + newfilname;

FileUtil.saveFile(path, file);

return "/images/touxiang/"+newfilname;

} else {

return "0";

}

}

其中saveFile方法代码如下

public static void saveFile(String savePath, File upload) {

try {

InputStream in = null;

OutputStream out = null;

in = new FileInputStream(upload);

out = new FileOutputStream(savePath);

int readed = 0;

byte[] buffer = new byte;

while ((readed = in.read(buffer, 0, 1024)) != -1) {

out.write(buffer, 0, readed);

}

out.flush();

out.close();

in.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

实现效果如下