2021-06-17

Java 上传图片
1、 布局
图片文本框放在form表单外面是因为图片不能用form表单提交
Form表单的重置不能重置到外面的input框。所以特别放在最上面
作为一个特别的知识点
//清空文件选择框
document.getElementById(“upPortrait”).outerHTML=document.getElementById(“upPortrait”).outerHTML;

<%--头像上传文本框--%>
头像

2、交互(图片上传部分的交互)
双击图片之后触发文件选择框
$("#userPicture").dblclick(function () {
KaTeX parse error: Expected 'EOF', got '#' at position 3: ("#̲upPortrait").cl…/i;
//创建一个文件读取对象
var imgReader = new FileReader();
//文件读取器读取到文件后的回调事件
imgReader.onload = function (event) {
//显示图片 base64编码的图片
$("#userPicture").attr(“src”, event.target.result);
}
$("#upPortraitDiv").on(‘change’,‘input[type=“file”]’,function () {
//获取出文件选择器中的第一个文件
var file = $("#upPortrait").get(0).files[0];
//判断文件选择类型
if (regexImageFilter.test(file.type)) {
//读取文件转换成URL把图片转为Base64编码
imgReader.readAsDataURL(file);
}else {
layer.alert(“请选择图片”);
}
});
2、 新增时图片(不管是新增还是修改,form表单都需要重置,特别的是form表单重置不了文件选择框)
//清空文件选择框
document.getElementById(“upPortrait”).outerHTML=document.getElementById(“upPortrait”).outerHTML;
3、修改时的图片回填显示
if (jsonMsg.data.portrait!=undefined && jsonMsg.data.portrait!=null && jsonMsg.data.portrait!=""){
有图片则在图片存放文件中提取出来
KaTeX parse error: Expected 'EOF', got '#' at position 3: ("#̲userPicture").p…{ctx}/user?method=getPortraitImage&imgName=’+jsonMsg.data.portrait);
}else {
没有则放一个假图片
KaTeX parse error: Expected 'EOF', got '#' at position 3: ("#̲userPicture").p…{ctx}/static/images/uploadImg.png’);
}
4、 图片回填需要通过servlet中的方法去查找图片

在servlet类中1、需要指定一个存放图片的目录
private static final String UPLOAD_PATH=“E:/z/javaProjectUp/BaseAdmin/user/”;
根据图片名返回图片流
public void getPortraitImage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取参数
String imgName=request.getParameter(“imgName”);
if (Tools.isNotNull(imgName)){
//图片名不未空
String imgPath=UPLOAD_PATH+imgName;
File fileImg=new File(imgPath);
if (fileImg.exists()){
//指定返的类型
response.setContentType(Tools.getImageContentType(imgName));

        InputStream in=null;
        OutputStream out=null;
        try {
            in= new FileInputStream(fileImg);
            out=response.getOutputStream();
            //复制
            // byte[] buff=new byte[1024*1024*10];//10M
            // int count=0;
            // while ((count=in.read(buff,0,buff.length))!=-1){
            //     out.write(buff,0,count);
            // }
            //commons-io
            IOUtils.copy(in,out);
            out.flush();
        }finally {
            if (in!=null)in.close();
            if (out!=null)out.close();
        }

    }
}

}

servlet新增部分
public void insert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JsonMsg jsonMsg=new JsonMsg();
//判断表单是否是文件上传的表单
if (!ServletFileUpload.isMultipartContent(request)){
// 如果不是则停止
jsonMsg.setMsg( “Error: 表单必须包含 enctype=multipart/form-data”);
returnJson(response,jsonMsg);
}

SimpleDateFormat dateFormat=new SimpleDateFormat(“yyyyMMdd_HHmmssSSS_”);
//配置上传相关的参数
DiskFileItemFactory factory=new DiskFileItemFactory();
//设置存临界值 - 超过后将产生临时文件并存储于临时目录中
factory.setSizeThreshold(MEMORY_THRESHOLD);

//设置临时存储目录
factory.setRepository(new File(System.getProperty(“java.io.tmpdir”)));
ServletFileUpload upload=new ServletFileUpload(factory);
//设置文件最大值 30M
upload.setFileSizeMax(MAX_FILE_SIZE);
//设置请求的大小最大值
upload.setSizeMax(MAX_REQUEST_SIZE);

//中文编码
upload.setHeaderEncoding(“UTF-8”);

//判断文件存放目录是否存在
File uploadDir=new File(UPLOAD_PATH);
if (!uploadDir.exists()){
uploadDir.mkdirs();
}

SysUser saveUser=new SysUser();
//解析请求内容,提前文件 和 普通参数

try {
List fileItems=upload.parseRequest(request);

if (fileItems != null && fileItems.size() > 0){
    //遍历
    for (FileItem item:fileItems) {
        //获取自动名称 -- 参数名request.getParameter("")
        String fieldName=item.getFieldName();
        //判断是文件 还是普通字段
        if (!item.isFormField()){
            //不是表单元素  文件
            if ("portrait".equals(fieldName)){//判断是否是头像文件
                //拼接文件名  item.getName()--》文件名
                String fileName=dateFormat.format(new Date())+System.nanoTime()+Tools.getFileExt(item.getName());
                //存放路径
                String filePath=UPLOAD_PATH+fileName;
                File saveFile=new File(filePath);
                System.err.println(filePath);
                //保存文件到硬盘
                item.write(saveFile);
                //把文件名保存到需要新增的对象中
                saveUser.setPortrait(fileName);
            }

}
}
}else{
jsonMsg.setMsg(“参数异常”);
}
} catch (FileUploadBase.SizeLimitExceededException e) {
e.printStackTrace();
jsonMsg.setMsg(“您上传文件超过了上传文件” + MAX_FILE_SIZE + “M 的限制”);
} catch (FileUploadException e) {
e.printStackTrace();
jsonMsg.setMsg(“文件上传失败”);
} catch (RuntimeException e) {
e.printStackTrace();
//数据校验失败的异常信息
jsonMsg.setMsg(e.getMessage());
}catch (Exception e) {
e.printStackTrace();
jsonMsg.setMsg(“表单提交失败”);
}
returnJson(response,jsonMsg);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值