图片上传

本文详细介绍了如何使用HTML、JS和Java实现图片上传功能,包括前端页面设计、文件类型验证及后端处理流程。从HTML表单构造到Java后端文件保存,全面解析图片上传的技术细节。

图片上传笔记整理

1.HTML代码

<form id="importForm" enctype="multipart/form-data" method="post">
                <table cellpadding="5">
                    <tr>
                        证件照片上传:
                    </tr>
                    <tr>
                        <input type="file" name="file" id="file" multiple="false" accept=".jpg,.jepg,.png,.gif" style="display:block;"/>
                        <span id = "imageSpan">未上传</span>
                    </tr>
                </table>
            </form>

2.js代码

 function excelUpload() {
            $.messager.confirm("上传提示","请上传图片!", function(r){
                if(r){
                    var formData = new FormData($("#importForm")[0]);
                    var imgName = $("#file").val();
                    var  idx = imgName.lastIndexOf(".");
                    if (idx != -1){
                        var  ext = imgName.substr(idx+1).toUpperCase();
                             ext = ext.toLowerCase( );
                        if (ext != 'jpg' && ext != 'png' && ext != 'jpeg' && ext != 'gif'){
                            alert("只能上传.jpg  .png  .jpeg  .gif类型的文件!");
                            return;
                        }
                    }else {
                        alert("只能上传.jpg  .png  .jpeg  .gif类型的文件!");
                        return;
                    }
                        $.ajax({
                        url:me.actionUrl +'uploadImage.do',
                        type:'post',
                        data:formData,
                        dataType:'json',
                        processData: false,
                        contentType: false,
                        success:function(data){
                            if(data.isOk == 1){
                                $.messager.alert('上传','上传成功');
                                $("#creditCodePath").val(data.realPath);
                                $("#imageSpan").html("已上传");
                            }else{
                                $.messager.alert('上传',data.message);
                            }
                        },
                        error:function(){
                            $.messager.alert('上传',"上传失败!");
                        }
                    })
                }
            })
        }

3.java代码

 @RequestMapping(value = "uploadImage")
   public void uploadImage(@RequestParam(name="file")MultipartFile file, HttpServletRequest request,HttpServletResponse response) {
       InputStream is = null;
       BufferedInputStream bis = null;
       FileOutputStream fos = null;
       BufferedOutputStream bos = null;
       String tarFileName = null;
       String realPath = null;
       Map map = new HashMap();
       map.put("isOk", 0);
       try {
           is = file.getInputStream();
           String fileName = file.getOriginalFilename();
           String path1 = request.getSession().getServletContext().getRealPath("/");
           //String parentpath = new File(path1).getParent();//获取项目的上一级目录
           //String parentpath2 = new File(parentpath).getParent();//获取项目的上一级目录
           //String filePath = parentpath2 + "/src/main/webapp/static/uploadImages/";//文件路径
           String filePath = path1 + "/upload/unitImages/";
           bis = new BufferedInputStream(is);
           //自动建立文件夹
           File folder = new File(filePath);
           if(!folder.exists()) {
               folder.mkdirs();
           }
           //String tarFileName = FileUtils.uploadFile(is, fileName, filePath);
           tarFileName = (fileName).substring(0,fileName.lastIndexOf(".")) + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + (fileName).substring(fileName.lastIndexOf("."));
           realPath = filePath + tarFileName;
           //String pathName =path1 +"static/uploadImages/" + tarFileName;
           String pathName ="/upload/unitImages/" + tarFileName;
           //构建文件输出流
           fos = new FileOutputStream(new File(realPath));
           //构建输出缓冲区,提高写文件的性能
           bos = new BufferedOutputStream(fos);
           //通过输入流读取数据并将数据通过输出流写到硬盘文件夹
           byte[] buffer = new byte[4096]; //构建4k的缓冲区
           int s = 0;
           while((s = bis.read(buffer)) != -1) {
               bos.write(buffer, 0, s);
               bos.flush();
           }
           map.put("isOk", 1);
           //map.put("realPath", realPath);
           map.put("realPath", pathName);
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }finally {
           if(bos != null) {
               try {
                   bos.close();
                   bos = null;
               } catch (IOException e) {
                   e.printStackTrace();

               }
           }
           if(fos != null) {
               try {
                   fos.close();
                   fos = null;
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
           if(bis != null) {
               try {
                   bis.close();
                   bis = null;
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
           if(is != null) {
               try {
                   is.close();
                   is = null;
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
       }
       ResultUtils.write(response, map);
   }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值