public void uploadpic() throws Exception{
ServletActionContext.getResponse().setCharacterEncoding("utf-8");
//获取session
admin=(Admin)ServletActionContext.getRequest().getSession().getAttribute("admin");
String imgpath="";
if(file1 != null){
if(file1.getName().endsWith(".exe")){
imgpath="对不起,你上传的文件格式不允许!!!";
ServletActionContext.getResponse().getWriter().print(imgpath);
}else{
FileInputStream inputStream = new FileInputStream(file1); //重新解析图片 上传过来的变强制转换为tmp了
String srcpath = Constants.ADMIN_BUILDJS+"images/tmp/subject_"+file1.getName().replace(".tmp", ".jpg");
File folder = new File(srcpath.substring(0, srcpath.lastIndexOf("/")));
if(!folder.exists()){
folder.mkdirs();
}
FileOutputStream outputStream = new FileOutputStream(srcpath);
byte[] buf = new byte[1024];
int length = 0;
while ((length = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, length);
}
inputStream.close();
outputStream.flush();
File newimg = new File(srcpath);
imgpath = fileService.uploadPhotoForGuide(newimg, newimg.getName(), new int[] { 600, 200 }, 18, admin.getAdid());
}
}
ServletActionContext.getResponse().getWriter().print(imgpath);
}
function uploadpic2(){
popup("图片上传","<div id='cgong' style='display:none; margin-left: 90px;margin-top: 60px; line-height: 30px;'>" +
"<span id='sucmsg' style='color:#ff0000;'></span></div><div id='msgok'></span>" +
"<input id='file1' type='file' size='31' name='file1'/><br />" +
"<input type='button' class='upload_btn' style='line-height: 35px; margin-left:200px;margin-top:10px;' value='确认上传' οnclick='usubmit2()'/></form>" +
"</div>",340,150,"");
}
function usubmit2(){
var s=$("#file1").val();
if(s!=null && s!=''){
$.ajaxFileUpload({
url:"subject!uploadpic.action",
secureuri:false,
fileElementId:'file1',
dataType:"text",
success: function (r){
alert(r);
}
});
}else{
alert('请选择图片文件');
}
}
//校验图片格式
if(/^.*?\.(gif|png|jpg|jpeg|bmp)$/.test(tmpFileValue.toLowerCase())){
return true;
} else {
alert("只能上传jpg、jpeg、png、bmp或gif格式的图片!");
return false;
}
<script type="text/javascript" src="${jspPath}/js/admin/ajaxfileupload.js"></script>
上面引用的文件 如果你是json 的话 需要对内部进行改造
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
data = r.responseText;
var start = data.indexOf(">");
if(start != -1) {
var end = data.indexOf("<", start + 1);
if(end != -1) {
data = data.substring(start + 1, end);
}
}
eval( "data = " + data );
// evaluate scripts within html