html
<form id="form_upload" enctype="multipart/form-data">
<input type="hidden" name="uid" id="upload_uid">
<input type="hidden" name="sid" id="upload_sid">
<div id="upload_fileArea">
<input type="file" class="btn_mask" οnchange="previewImage(this)" name="picture" style="display: none;" id="previewImg">
</div>
<span id="upload_include">
<span οnclick="upload_file()" class="btn btn-default btn_upload" id="btn_upload_file"><span class="glyphicon glyphicon-picture">上传图片</span></span>
</span>
</form>
js
/****遮罩层显示和隐藏****/
function upload(sid,sTitle){
$.get("user/findOne",{},function (user) {
if (user){
$(".shadow_upload").css({'display':'block'});
$('#upload_title').html(sTitle);
$('#upload_sid').val(sid);
var uid=user.uid;
$.get("fileUpload/findStatus",{uid:uid,sid:sid},function (info) {
if (info.flag){
}else {
var text=' <span class="btn btn-default btn_upload" id="btn_upload_file"><span class="glyphicon glyphicon-picture">上传图片</span></span>';
$('#upload_include').html(text);
$('#btn_upload_file').attr("disabled",true);
$('#message').html(info.errorMsg).show().delay(2000).fadeOut();
}
});
}else {
alert("请先进行登录!");
location.href="user_login.html";
}
});
}
$('#btn_close').click(function () {
$('.shadow').hide();
Refresh();
});
/***********图片预览**************/
//图片上传预览 IE是用了滤镜。
function previewImage(file)
{
var MAXWIDTH = 130;
var MAXHEIGHT = 130;
var div = document.getElementById('preview');
if (file.files && file.files[0])
{
div.innerHTML ='<img id=imghead οnclick=$("#previewImg").click()>';
var img = document.getElementById('imghead');
img.onload = function(){
var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
img.width = rect.width;
img.height = rect.height;
// img.style.marginLeft = rect.left+'px';
img.style.marginTop = rect.top+'px';
}
var reader = new FileReader();
reader.onload = function(evt){img.src = evt.target.result;}
reader.readAsDataURL(file.files[0]);
}
else //兼容IE
{
var sFilter='filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="';
file.select();
var src = document.selection.createRange().text;
div.innerHTML = '<img id=imghead>';
var img = document.getElementById('imghead');
img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src;
var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
status =('rect:'+rect.top+','+rect.left+','+rect.width+','+rect.height);
div.innerHTML = "<div id=divhead style='width:"+rect.width+"px;height:"+rect.height+"px;margin-top:"+rect.top+"px;"+sFilter+src+"\"'></div>";
}
}
function clacImgZoomParam( maxWidth, maxHeight, width, height ){
var param = {top:0, left:0, width:width, height:height};
if( width>maxWidth || height>maxHeight ){
rateWidth = width / maxWidth;
rateHeight = height / maxHeight;
if( rateWidth > rateHeight ){
param.width = maxWidth;
param.height = Math.round(height / rateWidth);
}else{
param.width = Math.round(width / rateHeight);
param.height = maxHeight;
}
}
param.left = Math.round((maxWidth - param.width) / 2);
param.top = Math.round((maxHeight - param.height) / 2);
return param;
}
/************图片上传*****************/
function upload_file(ele) {
//判断是否有文件
var fileinput=$('#previewImg').get(0).files[0];
if (fileinput){
var filePath=$("#previewImg").val();
//截取后缀名
var extStart=filePath.lastIndexOf(".");
var ext=filePath.substring(extStart,filePath.length).toUpperCase();
if (ext==".BMP"||ext==".PNG"||ext==".JPG"||ext==".JPEG"||ext==".GIF"||ext==".doc"||ext==".docx"||ext==".txt"){
//获取文件大小
var filesize=$('#previewImg')[0].files[0].size;
if (filesize<1024*1024){
var formData=new FormData($('#form_upload')[0]);
// $.post("upload/file",formData,function (info) {
//
// });
$.ajax({
type:'post',
url:"http://localhost:8055/firstblog/fileUpload/file",
data:formData,
cache:false,
processData:false,
contentType:false,
success:function () {
$('#message').html("上传成功").show().delay(2000).fadeOut();
setTimeout(Refresh,2000);
},
error:function () {
$('#message').html("上传失败").show().delay(2000).fadeOut();
}
});
}else {
alert("图片不能大于1M")
}
}else {
alert("文件限于bmp,png,gif,jpeg,jpg,doc,docx,txt格式");
return false;
}
}else {
alert("请选择上传文件");
}
}
/*******刷新******/
function Refresh() {
window.location.href=window.location.href;
}
后台
servlet
public void file(HttpServletRequest request, HttpServletResponse response) throws Exception {
//设置编码
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setContentType("utf-8");
//上传
Map<String,String> params=new HashMap<String,String>();
ResultInfo info=new ResultInfo();
FileUpload fileUpload=new FileUpload();
boolean isMultipart= ServletFileUpload.isMultipartContent(request);
if (isMultipart){//判断前台是否有mutipart属性
FileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload stf=new ServletFileUpload(factory);
//设置每一个item的头部字符编码,解决文件名的乱码问题
stf.setHeaderEncoding("UTF-8");
// //限制单个文件大小为1M
// stf.setFileSizeMax(1024*1024);
// //设置一次上传所有文件的最大值为5M
// stf.setSizeMax(1024*1024*5);
/**
* 通过parseRequest解析from中的所有请求字段,并保存到items集合中
* 即前台传地的spicture就保存在items中
*/
List<FileItem> items=stf.parseRequest(request);
for (FileItem fileItem:items){
//判断前台字段是普通form表单字段,还是文件字段
if (fileItem.isFormField()){
String name=fileItem.getFieldName();
String value=fileItem.getString("utf-8");
params.put(name,value);
String uid=params.get("uid");
String sid=params.get("sid");
String text_info=params.get("info");
if (uid !=null){
fileUpload.setUid(Integer.parseInt(uid));
}
if (sid != null){
fileUpload.setSid(Integer.parseInt(sid));
}
if (text_info != null){
fileUpload.setInfo(text_info);
}
}else {//picture
//文件上传
//文件名 getFiledName是获取普通表单字段的Name值
//getName()是获取文件名
String fileName= UuidUtil.getUuid()+"_"+fileItem.getName();
//获取文件内容并上传位置(服务器路径)
//获取服务器路径
//定义文件路径
String date= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
String path=request.getSession().getServletContext().getRealPath("upload/img/"+date);
File file=new File(path);
if (!file.exists()){
file.mkdirs();
}
File files=new File(path,fileName);
//获取文件大小
long size=fileItem.getSize();
//取整
size=Math.round(size/1024);
//文件写入
fileItem.write(files);
//封装数据
fileUpload.setfName(fileName);
//长整型转字符串
fileUpload.setfSize(String.valueOf(size));
//获取文件上传时间
String dateTime= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
fileUpload.setfAddTime(dateTime);
//保存上传路径
fileUpload.setFile_path(path);
System.out.println(fileUpload.getUid()+fileUpload.getSid());
}
}
}
System.out.println(fileUpload.getUid()+fileUpload.getSid());
boolean flag=service.save(fileUpload);
if (flag){
info.setFlag(true);
System.out.println("fileName"+"上传成功");
}else {
info.setFlag(false);
info.setErrorMsg("上传失败!");
}
ObjectMapper mapper=new ObjectMapper();
response.setContentType("application/json;charset=utf-8");
mapper.writeValue(response.getOutputStream(),info);
}