图片上传

html

<button type="button" class="btn btn-primary" οnclick="F_Open_dialog2()">Import</button>
<input type="file" id="btn_file2" style="display: none" onChange="imgview(this)" />  

js

 function F_Open_dialog2() {
document.getElementById("btn_file2").click();
}
       function imgview(ths ) {
// 判断图片格式是否合格
var filepath = document.getElementById(ths.id).value;
var re = /(\\+)/g;
var filename = filepath.replace(re, "#");
var one = filename.split("#");
var two = one[one.length - 1];
var imgName = two.split(".");
var suffix = imgName[imgName.length - 1];
var tp = "jpg,gif,png,JPG,GIF,PNG";
var rs = tp.indexOf(suffix);
var id = $(ths).parent().prev().attr("id");

if (rs >= 0) {
var fileObj = $(ths)[0].files[0];
var formData = new FormData();
formData.append("file", fileObj);
$.ajax({
url : '/gtm/rest/fileservice/photo' ,
type : 'POST' ,
data : formData ,
success : function(data, status ) {
if (data != null) {
var nextinp = $(ths).nextAll('img')[0];
$(nextinp).attr("src",data)
$($(ths).nextAll('input')[0]).val(data)
}
} ,
error : function(data, status, e ) {
} ,
cache : false ,
contentType : false ,
processData : false
});
return true;
} else {
ths.html("")
return false;
}
}

java

@POST
    @Path("photo")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public String uploadPhoto(@FormDataParam("file") InputStream fileInputStream,
            @FormDataParam("file") FormDataContentDisposition disposition) {
        if (fileInputStream != null) {
            String path = fileService.savePhoto(fileInputStream,request.getSession().getServletContext().getRealPath("/")+"img\\userPto\\");


            return path;
        }
        return null;
    }


  public String savePhoto(InputStream fileInputStream, String pathHead) {

 //将时间作为图片名
        String imageName = System.currentTimeMillis() + ".jpg";
        String newPath = UPLOADPATH + imageName;
        String result = PATH + imageName;
        OutputStream fop = null;
        File file;
        try {
 //创建文件
            file = new File(newPath);
            fop = new FileOutputStream(file);
            if (!file.exists()) {
                file.createNewFile();
            }
            int read = 0;
            byte[] bytes = new byte[1024];
//写文件
            while ((read = fileInputStream.read(bytes)) != -1) {
                fop.write(bytes, 0, read);
            }
            fop.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fop != null) {
                    fop.close();
                }
                return result;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值