js中图片上传回显功能
方法一:(mike)
$filePath=URL.createObjectURL(this.files[0]);
$('#editDevicePhoto').attr('src',$filePath);
方法二:
var file =document.getElementById("file");
var imgUrl =window.URL.createObjectURL(file.files[0]);
var img =document.getElementById('imghead');
img.setAttribute('src',imgUrl);
ajax处理
方法一:(mike)
var formData = new FormData();
formData.append("id",$("#selectDeviceId").val())
formData.append("file",file);
$.ajax({
type: 'POST',
url: '/decive/uploadDeviceImage',
data: formData,
dataType: 'JSON',
cache: false,
processData: false,
contentType: false,
success: function(data) {
.....
}
方法二:
var formData = new FormData($( "#uploadForm" )[0]);
$.ajax({
url: '<%=basePath%>UploadImage' ,
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
document.getElementById("showpic").src="<%=basePath%>UploadImage?picture=showpic";
}
后台处理:
方法一:(mike)
@ResponseBody
@RequestMapping(value = "/uploadDeviceImage")
public ReturnData uploadImage(MultipartFile file, String id) {
ReturnData rd = new ReturnData();
try {
if (file != null) {
jsupload(file, id);
rd = new ReturnData().success();
}
} catch (Exception e) {
rd = new ReturnData().fail();
}
return rd;
}
public void jsupload(MultipartFile multipartFile, String id) throws IOException {
if (!multipartFile.isEmpty()) {
String saveName = "";
String saveSrc = "";
//saveSrc = getKey_Src();
saveSrc = getPicture_Src();
saveName = id + ".png";
byte[] bytes = multipartFile.getBytes();
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
new FileOutputStream(new File(saveSrc + saveName)));
bufferedOutputStream.write(bytes);
bufferedOutputStream.close();
}
}
public String getPicture_Src(){
String server_path = UploadUtil.getProperties("web.upload-img-path");
String server_site_path = UploadUtil.getProperties("web.upload-picture-path");
File f = new File(server_path + server_site_path);
if (!f.exists())
f.mkdirs();
return server_path + server_site_path;
}
方法二:
@RequestMapping("/uploadPic")
@ResponseBody
public ResponseView addProduct(MultipartFile file, Integer picNum){
ResponseView rv = new ResponseView();
//构建文件目录
File uploadDir = new File("F:/DreamCinemaImg");
//如果目录不存在,则创建
if(!uploadDir.exists()){
uploadDir.mkdir();
}
//获取上传的文件名
String fileName = file.getOriginalFilename();
//构建一个完整的文件上传对象
File uploadFile = new File(uploadDir.getAbsolutePath() + "/" + fileName);
//判断文件是否存在
if(!uploadFile.exists()) {
try {
//通过transferTo方法进行上传
file.transferTo(uploadFile);
rv.setCode(0);
//把文件名放入响应视图
rv.setData(fileName);
} catch (IOException e) {
e.printStackTrace();
rv.setCode(500);
throw new RuntimeException(e.getMessage());
}
}else{
rv.setCode(400);
}
return rv;
}