js+ajax图片上传到服务器
效果:
Html
<form id=”myForm” action=”actorInfo_save” method=”post”>
<input type=”hidden” id=”clicktype” name=”clicktype” value=”${clicktype }” />
<input type=”hidden” name=”id” value=”${vbd.id}”>
<div class=”col-md-6″>
<label>职业</label>
<input type=”text” name=”occupation” class=”myinput” value=”${vbd.occupation}”>
</div>
<div class=”col-md-6″>
<div class=”col-md-12″>
<label>血型</label>
<!– <input type=”text” name=”” class=”myinput” value=””> –>
</div>
<div class=”row”>
<div class=”col-md-12″>
<label>配图</label>
<input type=”hidden” id=”picture” name=”picture” value=”${vbd.picture}”>
<img id=”headPic” name=”headPic” alt=”请上传封面照片” src=”${vbd.picture}” onerror=”this.src=\’../img/logo.jpg\'” style=\’width:240px;height:266px;line-height: 260px;text-align: center;\’>
<span id=”uploadspan” class=”btn btn-success fileinput-button” >
<span>上传</span>
<input id=”upload” name=”upload” type=”file” accept=”image/gif,image/jpeg,image/jpg,image/png,image/svg” >
</span>
</div>
</div>
</div>
<div class=”col-md-6″>
<div class=”row”>
<div class=”col-md-12″>
<label>主要作品</label>
<input type=”text” name=”magnum_opus” class=”myinput” value=”${vbd.magnum_opus}”>
</div>
</div>
</div>
</form>
Css略过……
Js
//图片上传
$(function () {
//只有选择不同图片才会调用,选择同一张不会调用
$(“#uploadspan”).change(function (e) {
//console.log(e.target.files[0])
var file = e.target.files[0] || e.dataTransfer.files[0];
if (file) {
var reader = new FileReader();
reader.onload = function () {
$(“#headPic”).attr(“src”, this.result);
}
reader.readAsDataURL(file);
//调用上传接口,拿到服务器图片地址,提交表单直接提交服务器src
saveImage();
}
});
})
function saveImage() {
//var file = $(“#file”).prop(\’files\’);file[0].src
// var file=$(“#upload”);
var formData = new FormData();
formData.append(\’upload\’, $(“#upload”)[0].files[0]);
$.ajax({
url: “../upload/img”,//文档接口
type: “post”,
data: formData,
contentType: false,
processData: false,
mimeType: “multipart/form-data”,
success: function (data) {
$(“#picture”).val(“../upload/images/”+data);
console.log(data);
alert(\’上传成功\’)
},
error: function (data) {
alert(\’上传失败\’)
}
});
}
Java接口
package com.wasu.controller;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.sun.tools.javac.util.Log;
@Controller
@RequestMapping(“upload”)
public class UploadController {
@Autowired
private HttpServletRequest request;
@ResponseBody
@RequestMapping(“img”)
public String uploadFilesSpecifyPath(@RequestParam(“upload”) MultipartFile uploadImg)
throws Exception {
String realpath=””;
if(uploadImg!=null){
long size= uploadImg.getSize();
if(size < 10485760){//文件设置大小,我这里设置10M。
String name = uploadImg.getOriginalFilename();//直接返回文件的名字
String subffix = name.substring(name.lastIndexOf(“.”) + 1, name.length());//我这里取得文件后缀
String fileName=UUID.randomUUID().toString();//文件保存进来,我给他重新命名,数据库保存有原本的名字,所以输出的时候再把他附上原本的名字就行了。
String filepath=request.getRealPath(“/”) + “upload\\images\\”;//获取项目路径到webapp
File file=new File(filepath);
if(!file.exists()){//目录不存在就创建
file.mkdirs();
}
uploadImg.transferTo(new File(file+”\\”+fileName+”.”+subffix));//保存文件
realpath=fileName+”.”+subffix;
}
}
return realpath;
}
/**
* 返回斜杠拼接的字符串
* @param args
* @return
*/
public static String mergeStringWithSeparator(String…args){
StringBuilder sb=new StringBuilder();
for (String arg : args) {
sb.append(arg);
sb.append(File.separator);
}
return sb.substring(0, sb.length()-1).toString();
}
public Object add(HttpServletRequest request,@RequestParam( value=”files”,required=false)MultipartFile multipartFile) throws IllegalStateException, IOException {//这里一定要写required=false 不然前端不传文件一定报错。到不了后台。
String realpath=””;
//获取文件名
String name=””;
if(multipartFile!=null){
long size= multipartFile.getSize();
if(size >5242880){//文件设置大小,我这里设置5M。
name=multipartFile.getOriginalFilename();//直接返回文件的名字
String subffix = name.substring(name.lastIndexOf(“.”) + 1, name.length());//我这里取得文件后缀
String fileName=”123″;//文件保存进来,我给他重新命名,数据库保存有原本的名字,所以输出的时候再把他附上原本的名字就行了。
String filepath=request.getRealPath(“/”) + “upload\\images\\”;//获取项目路径到webapp
File file=new File(filepath);
if(!file.exists()){//目录不存在就创建
file.mkdirs();
}
multipartFile.transferTo(new File(file+”\\”+fileName+”.”+subffix));//保存文件
realpath=file+”\\”+fileName+”.”+subffix;
}
}
return realpath;
}}