form表单图片上传的HTML代码
form表单提交处理
Java控制层返回页面结构
页面图片取得上传 Java
页面取图片显示
<input type="file" id="myfiles" name="myfiles">
<div style="margin-top:10px;height:auto;" class="clearfix">
<button type="submit" class="btn btn-primary start" style="float: left;padding: 0 20px;margin-right:12px;"><i class="en-upload"></i><span>确定</span></button>
<button type="button" id="cencle" class="btn btn-primary start" style="float: left;padding: 0 20px;margin-right:12px;"><i class="en-upload"></i><span>取消</span></button>
<img id="imgShow0" name="imgShow0" src="" width="150px" height="150px;margin-left: 26px;">
</div>
js代码控制后缀名,图片大小及在线浏览
$("#myfiles").change(function() {
var f = document.getElementById("myfiles").value;
var imagSize = document.getElementById("myfiles").files[0].size;
if (f == "") {
alert("请上传图片");
return false;
} else {
if(imagSize>1024*500){
alert("图片大小要求在500KB以内");
$("#myfiles").val("");
return false;
}
if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(f)) {
alert("图片类型必须是.gif,jpeg,jpg,png,bmp中的一种");
$("#myfiles").val("");
return false;
}
}
var objUrl = getObjectURL(this.files[0]);
console.log("objUrl = " + objUrl);
if (objUrl) {
$("#imgShow0").attr("src", objUrl);
}
});
//建立一個可存取到該file的url
function getObjectURL(file) {
var url = null;
if (window.createObjectURL != undefined) { // basic
url = window.createObjectURL(file);
} else if (window.URL != undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file);
} else if (window.webkitURL != undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file);
}
return url;
}
form表单提交处理
@RequestMapping(params = "doupload",method = RequestMethod.POST)
public ModelAndView doupload(InesvGiftEntity inesvGift,@RequestParam MultipartFile myfiles,
HttpServletResponse rsp,HttpServletRequest request) {
Map<String, Object> result = new HashMap<String, Object>();
ModelMap modelMap = new ModelMap();
//初始默认返回
modelMap.put("result", 0);
boolean flag = false;
String message = "";
// 新文件名
String fileName[] = new String[2];
// 原文件名
String oldFileName = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");//日期格式
InputStream file = null;
int i = 0;
if(!myfiles.isEmpty()){
if (!myfiles.isEmpty()) {
//如果用的是Tomcat服务器,则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\文件夹中
oldFileName = myfiles.getOriginalFilename();
// 拼接文件名
fileName[i] = sdf.format(new Date()) + oldFileName.substring(oldFileName.lastIndexOf("."), oldFileName.length());
try {
file = myfiles.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
if (file != null) {
//这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉,我是看它的源码才知道的
try {
//存放在本地
//System.out.println(request.getSession().getServletContext().getRealPath("/"));
//System.out.println(request.getSession().getServletContext().getRealPath("/")+"/imgfile");
String imgcacheurl ="/picture";
File img=new File(imgcacheurl, fileName[i]);
if(img.length()<512000){
copyInputStreamToFile(file,img);
}else{
message = "图片大小不能超过500KB";
}
} catch (IOException e) {
e.printStackTrace();
}
}
try{
message = "操作成功";
flag = true;
modelMap.put("result", 1);
inesvGift.setPictureUrl(fileName[0]);
inesvGift.setStatus(1);
inesvGift.setGiftTime(new Date());
inesvGiftService.save(inesvGift);
}catch(Exception e){
e.printStackTrace();
message = "操作失败";
}
}else{
message = "请选择礼品图片";
}
getScript(rsp,message);
return new ModelAndView("com/inesv/inesvGift",result);
//return list(request);
}
//复制文件
public static void copyInputStreamToFile(InputStream source, File destination) throws IOException {
try {
destination.length();
FileOutputStream output = FileUtils.openOutputStream(destination);
try {
IOUtils.copy(source, output);
output.close(); // don't swallow close Exception if copy completes normally
} finally {
IOUtils.closeQuietly(output);
}
} finally {
IOUtils.closeQuietly(source);
}
}
Java控制层返回页面结构
/**
* 直接输出script脚本到前台
*
* @param rsp
* @param scriptStr
*/
public static void getScript(HttpServletResponse response, String script) {
PrintWriter pw = null;
try {
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache");
pw = response.getWriter();
pw.println("<script language='javascript'>");
pw.println("alert('" + script + "')");
pw.println("history.go(-2)");
pw.println("</script>");
pw.flush();
} catch (Exception e) {
} finally {
if (pw != null) {
pw.close();
}
}
}
页面图片取得上传 Java
/**
* 取得上传的图片
* @param rsp
* @param path
*/
@RequestMapping(params = "getImage",method = RequestMethod.GET)
public void getImage(HttpServletResponse rsp,String value){
OutputStream out = null;
try {
if (!value.equals("") && value!=null) {
out = rsp.getOutputStream();
FileInputStream fin = null;
String imgcacheurl = "/picture";
try {
fin = new FileInputStream(imgcacheurl+"/"+value);
int c;
while((c=fin.read())!=-1)
{
out.write(c);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (fin != null) {
fin.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
页面取图片显示
<t:dgCol title="图片" field="pictureUrl" formatterjs="picture" queryMode="group" width="120"></t:dgCol>
function picture(value) {
var img = "inesvGiftController.do?getImage&value=" + value;
var str = "<img class='imgW' style='width: 80px;height:80px;cursor: pointer;' src="+img+">";
return str;
}