<input type="file" value="上传图片" name="photo" id="uploadPhoto" >
<button class="btn btn-default" type="button" οnclick="uploadFile()" value="上传"> 上传</button>
function uploadFile(){
if(!$("#uploadPhoto").val()){
alert("请选择需要上传的图片");
return false;
}
$.ajaxFileUpload ({
url: '../../../loadfile/uploadfile.action', //用于文件上传的服务器端请求地址
secureuri: false, //是否需要安全协议,一般设置为false
fileElementId: 'uploadPhoto', //文件上传域的ID
dataType: 'json', //返回值类型 一般设置为json
//服务器成功响应处理函数
success:function (data, status) {
alert(data);
$("#photonPk").val(data.message);
$("#showDevPic").attr("src","../../../loadfile/showPic.action?sysPk="+data.message)//取图片
},
//服务器响应失败处理函数
error:function (data, status, e){
alert("as:"+e);
}
} );
return false;
}
action中:
private File photo;
private List<String> fileContentType;
private SystemAttachmentService attachmentService;
private Long objectId;
private Long sysPk;
/get set 方法/
@Action("uploadfile")
public String upLoadPic() throws Exception {
SystemAttachment ssa = new SystemAttachment();
byte[] byte_photo = FileCopyUtils.copyToByteArray(getPhoto());
ssa.setContent(byte_photo);
ssa.setCreateTime(new Date());
ssa.setCreateUser(getCurrentUserCode());
ssa.setDeleteFlag(0l);
Long pk = attachmentService.saveSystemAttach(ssa);
getJson().put("message", pk);
return "forjson";
}
@Action("showPic")
public String showViewPic() {
OutputStream out = null;
SystemAttachment ss = null;
if(null!=objectId){
ss = attachmentService.querySysPicForObjectId(objectId);
}else{
ss = attachmentService.querySysPicForSyspk(sysPk);
}
try {
out = getHttpServletResponse().getOutputStream();
if (null != ss) {
try {
out.write(ss.getContent());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
out.write(attachmentService.querySysPicForObjectId(0l).getContent());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}