Ajax上傳圖片,后臺使用SpringBoot的MultipartFile類型接收的問題

Ajax很好用,但是在上傳文件這邊卻總是會出問題。例如,現(xiàn)在想上傳一張圖片,希望前臺無刷新操作,使用Ajax上傳,后臺接收不到相應(yīng)的類型,導(dǎo)致上傳失敗,但是如果使用input和submit組合又會出現(xiàn)頁面刷新的情況,百般折磨后找到了一個新的工具:Simple-Ajax-Uploader.

簡單示例

前端代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button id="btnUpload">上傳圖片</button>
<script type="text/javascript" src="SimpleAjaxUploader.js"></script>
<script type="text/javascript">
    var btnUpload = document.getElementById("btnUpload");
    var uploader = new ss.SimpleUpload({
        button: btnUpload,
        url: "http://192.168.1.105:8080/api/file/upload/image",
        name: "uploadImage",
        multiple: true,
        allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
        responseType: 'json',
        onSubmit: function () {

        },
        onComplete: function (filename, response) {
            console.log(filename);
            console.log(response);
        },
        onError: function (error) {
            console.log(error);
        }
    });
</script>
</body>
</html>

后臺代碼

    /**
     * 單張圖片上傳接口
     *
     * @param request     請求
     * @param uploadImage 要上傳的圖片
     * @return 上傳成功返回圖片的URL;上傳失敗返回“上傳失敗”;
     */
    @ApiOperation(value = "單張圖片上傳接口")
    @RequestMapping(value = "/upload/image", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public HttpResponse<String> uploadImage(HttpServletRequest request, MultipartFile uploadImage) {
        HttpResponse<String> httpResponse = new HttpResponse<>();
        if (null != uploadImage) {
            String uploadImagePath = request.getSession().getServletContext().getRealPath("/") + "/file/upload/image/";
            File uploadImageDir = new File(uploadImagePath);
            if (!uploadImageDir.exists()) {
                boolean success = uploadImageDir.mkdir();
                if (success) {
                    System.out.println("文件夾創(chuàng)建成功");
                } else {
                    System.out.println("文件夾創(chuàng)建失敗");
                }
            }
            // 初始化圖片信息
            Image image = initImage(uploadImage);
            // 要保存的圖片
            File saveToServerImage = new File(uploadImagePath + image.getName());
            try {
                // 將要上傳的圖片信息寫入要保存的圖片中
                uploadImage.transferTo(saveToServerImage);
                // 將圖片信息存儲到數(shù)據(jù)庫
                Image saveToDbImage = imageJPA.save(image);
                if (null != saveToDbImage) {
                    httpResponse.setCode(1);
                    httpResponse.setData(saveToDbImage.getUrl());
                    httpResponse.setMsg("圖片上傳成功");
                    return httpResponse;
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
        httpResponse.setCode(0);
        httpResponse.setData("");
        httpResponse.setMsg("圖片上傳失敗");
        return httpResponse;
    }

這樣就可以無刷新解決問題啦。


upload.gif
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,765評論 25 709
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,506評論 19 139
  • 李重凰閱讀 275評論 0 1
  • 第五目沒有寫關(guān)于文章的內(nèi)容,反而介紹起閱讀的書籍了。 事情的起因是中秋節(jié)到了,大文和樂華兩家人一起過中秋,剛好大文...
    kww007閱讀 533評論 0 0
  • 今天結(jié)合市調(diào)繼續(xù)學(xué)習(xí)稻盛和夫案例。 在稻盛和夫的著作《活法》中稻盛先生闡述了一種被稱為“智慧之井”的地方。當(dāng)一個人...
    快樂稀飯閱讀 424評論 0 0

友情鏈接更多精彩內(nèi)容