Ajax简单异步上传图片并回显

前台代码

上传图片按钮

<a href="javascript:void(0)" onclick="uploadPhoto()">选择图片</a>

隐藏的文件选择器

<input type="file" id="photoFile" style="display: none;" onchange="upload()">

图片预览

<img id="preview_photo" src="" width="200px" height="200px">

去除图片预览未选择时默认时的边框

<style>
    img[src=""],img:not([src]){
        opacity:0;
    }
</style>

JavaScript部分

<script>
    function uploadPhoto() {
        $("#photoFile").click();
    }

    /**
     * 上传图片
     */
    function upload() {
        if ($("#photoFile").val() == '') {
            return;
        }
        var formData = new FormData();
        formData.append('photo', document.getElementById('photoFile').files[0]);
        $.ajax({
            url:"${pageContext.request.contextPath}/system/uploadPhoto",
            type:"post",
            data: formData,
            contentType: false,
            processData: false,
            success: function(data) {
                if (data.type == "success") {
                    $("#preview_photo").attr("src", data.filepath+data.filename);
                    $("#productImg").val(data.filename);
                } else {
                    alert(data.msg);
                }
            },
            error:function(data) {
                alert("上传失败")
            }
        });
    }
</script>

后台代码

    /**
     * 图片上传
     * @param photo
     * @param request
     * @return
     */

    @RequestMapping(value="/upFile",method = RequestMethod.POST)
    @ResponseBody
    public Object upFile(HttpServletRequest request,@RequestParam(value="file",required=false) MultipartFile file) throws Exception{
      System.out.println("=====upFile======");
      String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
      Map<String,Object> map = new HashMap<String,Object>();
      String ffile = DateUtil.getDays(), fileName = "";
      if (null != file && !file.isEmpty()) {
         String filePath = PathUtil.getClasspath() + Const.FILEPATHIMG + ffile; //文件上传路径
        fileName = FileUpload.fileUp(file, filePath, this.get32UUID()); //执行上传
        map.put("filePath",Const.FILEPATHIMG + ffile + "/" + fileName);
        map.put("msg","success");
      }else{
        map.put("msg","上传失败");
      }
      return map;
}



工具类:FileUpload

public class FileUpload {

    /**上传文件
     * @param file             //文件对象
     * @param filePath        //上传路径
     * @param fileName        //文件名
     * @return  文件名
     */
    public static String fileUp(MultipartFile file, String filePath, String fileName){
        String extName = ""; // 扩展名格式:
        try {
            if (file.getOriginalFilename().lastIndexOf(".") >= 0){
                extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            }
            copyFile(file.getInputStream(), filePath, fileName+extName).replaceAll("-", "");
        } catch (IOException e) {
            System.out.println(e);
        }
        return fileName+extName;
    }
    
    /**
     * 写文件到当前目录的upload目录中
     * @param in
     * @param fileName
     * @throws IOException
     */
    private static String copyFile(InputStream in, String dir, String realName)
            throws IOException {
        File file = mkdirsmy(dir,realName);
        FileUtils.copyInputStreamToFile(in, file);
        return realName;
    }
    
    
    /**判断路径是否存在,否:创建此路径
     * @param dir  文件路径
     * @param realName  文件名
     * @throws IOException 
     */
    public static File mkdirsmy(String dir, String realName) throws IOException{
        File file = new File(dir, realName);
        if (!file.exists()) {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
        }
        return file;
    }
    
    
    /**下载网络图片上传到服务器上
     * @param httpUrl 图片网络地址
     * @param filePath    图片保存路径
     * @param myFileName  图片文件名(null时用网络图片原名)
     * @return    返回图片名称
     */
    public static String getHtmlPicture(String httpUrl, String filePath , String myFileName) {
        
        URL url;                        //定义URL对象url
        BufferedInputStream in;            //定义输入字节缓冲流对象in
        FileOutputStream file;            //定义文件输出流对象file
        try {
            String fileName = null == myFileName?httpUrl.substring(httpUrl.lastIndexOf("/")).replace("/", ""):myFileName; //图片文件名(null时用网络图片原名)
            url = new URL(httpUrl);        //初始化url对象
            in = new BufferedInputStream(url.openStream());                                    //初始化in对象,也就是获得url字节流
            //file = new FileOutputStream(new File(filePath +"\\"+ fileName));
            file = new FileOutputStream(mkdirsmy(filePath,fileName));
            int t;
            while ((t = in.read()) != -1) {
                file.write(t);
            }
            file.close();
            in.close();
            return fileName;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
        
    }
}

 

上一篇:servlet-response-download


下一篇:go文件操作