首先 jsp页面:
导入
<script src="js/jquery-2.1.1.js" type="text/javascript"></script>
<script src="js/ajaxfileupload.js" type="text/javascript"></script>
js代码:
<script type="text/javascript">
function ajaxFileUpload() {
//alert("aa");
$.ajaxFileUpload
(
{
url: 'ajaxUpload.action', //用于文件上传的服务器端请求地址
secureuri: false, //是否需要安全协议,一般设置为false
fileElementId: 'file1', //文件上传域的ID
dataType: 'text', //返回值类型 一般设置为json;注: 用json返回有点问题,这里用text返回存字符串
success:function(data)
{
$("#img1").attr("src", data);
//alert(data.message);
},
error: function (data, status, e)//服务器响应失败处理函数
{
alert(e);
}
}
);
return false;
}
</script>
body代码:
<body>
<p><input type="file" id="file1" name="file1" /></p>
<input type="button" value="上传" οnclick="return ajaxFileUpload()"/>
<p><img id="img1" alt="这是图片" src="" /></p>
</body>
struts.xm代码:
</pre><pre name="code" class="java"><action name="ajaxUpload" class="AdminAction" method="ajaxUpload"></action>
后台action代码:
private File file1; //file1 对应jsp页面的file的name
private String file1FileName;
private String file1ContentType;
//实现get和set......
public void ajaxUpload() throws Exception {
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html; charset=UTF-8"); //因为使用text类型,所以用text/html
String message = null;
String path = ServletActionContext.getServletContext().getRealPath("/photo"); //获得服务器下的photo路径
try {
File f = this.getFile1();
FileInputStream inputStream = new FileInputStream(f);
FileOutputStream outputStream = new FileOutputStream(path + "/"+ this.getFile1FileName());
//存储图片
byte[] buf = new byte[1024];
int length = 0;
while ((length = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, length);
}
inputStream.close();
outputStream.flush();
message = "http://localhost:8080/xxx/photo/"+this.getFile1FileName(); //返回的数据--图片的显示地址
} catch (Exception e) {
e.printStackTrace();
message = "上传异常!!!!";
}
response.getWriter().print(message);
}