美文网首页
ajax上传图片的小坑

ajax上传图片的小坑

作者: jenye_ | 来源:发表于2019-07-09 21:04 被阅读0次
$(function () {
    var input =  document.getElementById("file_input");  //这里如果用jq获取会用不了addEventListener
    alert(input);
    input.addEventListener('change',readFile,false);
    function readFile() {
        var file = this.files[0]; //获取file对象

        // 这里写一个ajax把通过post把this.files[0]提交到后台就可以了。
    }

    //
    //

});

完整代码:

$(function () {
    var input = document.getElementById("file_input");
    // alert(input);
    input.addEventListener('change', readFile, false);
    function readFile() {
        var file = this.files[0]; //获取file对象
        var formData = new FormData($("#uploadForm")[0])  //创建一个forData 
        formData.append('file', file) //把file添加进去  name命名为img
        $.ajax({
            url: "/upload_dp",
            data: formData,
            type: "POST",
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (data) {
                alert(data.url);
                //成功
            },
            error: function () {
                //失败
            }
        })
    }

    //
    //

});

controller:

    @Autowired
    UserService userService;
    @RequestMapping("/upload")
    @ResponseBody
    public ImgInfo setImgUrl(MultipartFile file, HttpServletResponse response, HttpServletRequest request,Integer isDp)
            throws Exception {
        File path2 = new File(ResourceUtils.getURL("classpath:static").getPath().replace("%20"," ").replace('/', '\\'));
        System.out.println(path2);
        if(!path2.exists()) path2 = new File("");
        //如果上传目录为/static/images/upload/,则可以如下获取:
        File upload2 = new File(path2.getAbsolutePath(),"img/upfile/");
        if(!upload2.exists()) upload2.mkdirs();
        String path=upload2.getAbsolutePath()+"/";

        // Get the file and save it somewhere
        byte[] bytes = file.getBytes();
//        System.out.println(new String(bytes));
//        String path = request.getServletContext().getRealPath("/image/");
        File imgFile = new File(path);
        if (!imgFile.exists()) {
            imgFile.mkdirs();
            System.out.println("文件创建成功!");
        }
        String fileName ="";
        //获得后缀
        fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        if (isDp != null){
             fileName = ""+userService.getNowUserId(request)+"dp."+suffix;// 文件名称
        }else {
             fileName = ""+ UUID.randomUUID()+file.getOriginalFilename();// 文件名称
        }

        System.out.println(path + fileName);

        try (FileOutputStream fos = new FileOutputStream(new File(path + fileName))) {
            int len = 0;
            fos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String value = "http://localhost:8080/img/upfile/" + fileName;
        String[] values = { value };

        ImgInfo imgInfo = new ImgInfo();
        imgInfo.setError(0);
        imgInfo.setUrl(values);

        System.out.println(imgInfo.toString());
        return imgInfo;
    }

imgInfo

package com.phoenix.zhihu.utils;

import java.util.Arrays;

public class ImgInfo {

    private Integer error;
    private String[] url;
    private int userid;

    public int getUserid() {
        return userid;
    }

    public void setUserid(int userid) {
        this.userid = userid;
    }



    public Integer getError() {
        return error;
    }

    public void setError(Integer error) {
        this.error = error;
    }

    public String[] getUrl() {
        return url;
    }

    public void setUrl(String[] url) {
        this.url = url;
    }

    @Override
    public String toString() {
        return "ImgInfo [error=" + error + ", url=" + Arrays.toString(url) + "]";
    }

}

相关文章

网友评论

      本文标题:ajax上传图片的小坑

      本文链接:https://www.haomeiwen.com/subject/kjzfkctx.html