经过好几天的间断研究终于研究出了如何成功上传和查询图片。
参考了好多:
http://www.cnblogs.com/heyuquan/p/form-plug-async-submit.html
jsp:
图片存储测试
<form id="imageForm" name="imageForm" enctype="multipart/form-data">
<input id="ID" name="ID" type="text" />
<input id="NAME" name="NAME" type="text" />
<input id="CONTENT" name="CONTENT" type="file" size="30" class="required" />
<input type="button" value="提交" οnclick="save()"/>
<input type="reset" value="重置">
</form>
<img id="uploadImage" alt="" src="">
js:
function save() {
$("#imageForm").ajaxSubmit({
url : ctx + "/uploadForImg/save",
type : 'POST',
dataType : 'json',
async : false,
success : function(json) {
if(json.success){
alert("上传图片成功!");
// window.location.href = ctx+"/img_view.jsp?id="+$("#ID").val();
$("#uploadImage").attr("src",ctx+"/uploadForImg/selectOne?id="+$("#ID").val());
// $("#myhref").attr("href",ctx+"/uploadForImg/selectOne?id="+$("#ID").val());
// $("#myhref").text("下载");
}else{
alert("提交失败!失败原因:"+json.message);
}
}
});
java:
@Before(JsonResultInterceptor.class)
public void save() throws Exception {
/**
* 处理blob
*/
UploadFile file = getFile("CONTENT");
FileInputStream input = new FileInputStream(file.getFile());
byte[] b = new byte[input.available()];
input.read(b);
input.close();
// 存入二进制字节流
HashMap<String, Object> parameters = (HashMap<String, Object>) getParams();
parameters.put("CONTENT", b);
System.out.println(parameters.size());
// ===============================
attachmentDAO.save(parameters);
}
/**
* 查询
*/
@Before(JsonResultInterceptor.class)
public void selectOne() throws Exception {
HashMap<String, Object> parameters = (HashMap<String, Object>) getParams();
HashMap<String, Object> result = new HashMap<String, Object>();
try {
result = (HashMap<String, Object>) attachmentDAO.queryOneData(parameters);
} catch (Exception e) {
e.printStackTrace();
}
/**
* 对blob的处理
*/
BufferedInputStream ins = null;// 取得BLOB的IO流
OutputStream ops = null;
byte[] bt = null;
try {
getResponse().setContentType("image/JPEG");
BLOB blob = (BLOB) result.get("CONTENT");
if (blob == null)
return;
InputStream is = blob.getBinaryStream();
ins = new BufferedInputStream(is);
int bufferSize = (int) blob.length();// 取得BLOB的长度
bt = new byte[bufferSize];
ins.read(bt, 0, bufferSize);
getResponse().getOutputStream().write(bt);
ops = getResponse().getOutputStream();
} catch (Exception e) {
e.printStackTrace();
}
ops.flush();
ops.close();
ins.close();
// =====================================
}
上面的注解是对从前台数据进行的json化