spring boot如何?圖片的上傳和下載(代碼)

來源:互聯網
上載者:User
本篇文章給大家帶來的內容是關於spring boot如何?圖片的上傳和下載(代碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所協助。

1,核心的controller代碼

package com.qwrt.station.websocket.controller;import com.alibaba.fastjson.JSONObject;import com.qwrt.station.common.util.JsonUtil;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Value;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.*;/** * Created by jack on 2017/10/30. */@RestController@RequestMapping("v1/uploadDownload")public class UploadDownloadController {    private static final Logger logger = LoggerFactory.getLogger(UploadDownloadController.class);    @Value("${uploadDir}")    private String uploadDir;    @RequestMapping(value = "/uploadImage", method = RequestMethod.POST)    public JSONObject uploadImage(@RequestParam(value = "file") MultipartFile file) throws RuntimeException {        if (file.isEmpty()) {            return JsonUtil.getFailJsonObject("檔案不可為空");        }        // 擷取檔案名稱        String fileName = file.getOriginalFilename();        logger.info("上傳的檔案名稱為:" + fileName);        // 擷取檔案的尾碼名        String suffixName = fileName.substring(fileName.lastIndexOf("."));        logger.info("上傳的尾碼名為:" + suffixName);        // 檔案上傳後的路徑        String filePath = uploadDir;        // 解決中文問題,liunx下中文路徑,圖片顯示問題        // fileName = UUID.randomUUID() + suffixName;        File dest = new File(filePath + fileName);        // 檢測是否存在目錄        if (!dest.getParentFile().exists()) {            dest.getParentFile().mkdirs();        }        try {            file.transferTo(dest);            logger.info("上傳成功後的檔案路徑未:" + filePath + fileName);            return JsonUtil.getSuccessJsonObject(fileName);        } catch (IllegalStateException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return JsonUtil.getFailJsonObject("檔案上傳失敗");    }    //檔案下載相關代碼    @RequestMapping(value = "/downloadImage",method = RequestMethod.GET)    public String downloadImage(String imageName,HttpServletRequest request, HttpServletResponse response) {        //String fileName = "123.JPG";        logger.debug("the imageName is : "+imageName);        String fileUrl = uploadDir+imageName;        if (fileUrl != null) {            //當前是從該工程的WEB-INF//File//下擷取檔案(該目錄可以在下面一行代碼配置)然後下載到C:\\users\\downloads即原生預設下載的目錄           /* String realPath = request.getServletContext().getRealPath(                    "//WEB-INF//");*/            /*File file = new File(realPath, fileName);*/            File file = new File(fileUrl);            if (file.exists()) {                response.setContentType("application/force-download");// 設定強制下載不開啟                response.addHeader("Content-Disposition",                        "attachment;fileName=" + imageName);// 設定檔案名稱                byte[] buffer = new byte[1024];                FileInputStream fis = null;                BufferedInputStream bis = null;                try {                    fis = new FileInputStream(file);                    bis = new BufferedInputStream(fis);                    OutputStream os = response.getOutputStream();                    int i = bis.read(buffer);                    while (i != -1) {                        os.write(buffer, 0, i);                        i = bis.read(buffer);                    }                    System.out.println("success");                } catch (Exception e) {                    e.printStackTrace();                } finally {                    if (bis != null) {                        try {                            bis.close();                        } catch (IOException e) {                            e.printStackTrace();                        }                    }                    if (fis != null) {                        try {                            fis.close();                        } catch (IOException e) {                            e.printStackTrace();                        }                    }                }            }        }        return null;    }}


上面的代碼有兩個方法,上面的方法是圖片上傳的方法,下面的方法是圖片下載的方法。下載圖片需要傳入圖片的檔案名稱,在ios,android手機,Google瀏覽器測試,上傳下載沒有問題。

2,測試的html的核心代碼如下,進行圖片的上傳和下載:

<!DOCTYPE html><html><head><meta charset="UTF-8" /><title>websocket chat</title></head><body><p><label>輸入資訊:</label><input id="id" width="100px" /><br /><button id="btn">發送訊息</button>    <button id="connection">websocket串連</button>     <button id="disconnection">斷開websocket串連</button><br /><br /><form enctype="multipart/form-data" id="uploadForm">          <input type="file" name="uploadFile" id="upload_file" style="margin-bottom:10px;">            <input type="button" id="uploadPicButton" value="上傳" onclick="uploadImage()">         </form><!--<input type="file" onchange="uploadImgTest();" id="uploadImg" name="uploadImg" /><button id="uploadImage" onclick="uploadImage();">上傳</button>--></p><p id="test"></p><hr color="blanchedalmond"/><p id="voicep"></p><hr color="chartreuse" /><p id="imgp" style="width: 30%;height: 30%;"><img src="http://192.168.9.123:8860/v1/uploadDownload/downloadImage?imageName=123.JPG" style="width: 160px;height: 160px;"/></p></body><script src="js/jquery-3.2.1.min.js"></script><!--<script th:src="@{stomp.min.js}"></script>--><script src="js/sockjs.min.js"></script><script>var websocketUrl = "ws://192.168.9.123:8860/webSocketServer";var websocket;if('WebSocket' in window) {//websocket = new WebSocket("ws://" + document.location.host + "/webSocketServer");//websocket = new WebSocket("ws://192.168.9.123:9092/webSocketServer");//websocket = new WebSocket("ws://localhost:8860/webSocketServer");websocket = new WebSocket(websocketUrl);} else if('MozWebSocket' in window) {websocket = new MozWebSocket("ws://" + document.location.host + "/webSocketServer");} else {websocket = new SockJS("http://" + document.location.host + "/sockjs/webSocketServer");}websocket.onopen = function(evnt) {console.log("onopen----", evnt.data);};websocket.onmessage = function(evnt) {//$("#test").html("(<font color='red'>" + evnt.data + "</font>)");console.log("onmessage----", evnt.data);//$("#test").html(evnt.data);$("#test").append('<p>' + event.data + '</p>');};websocket.onerror = function(evnt) {console.log("onerror----", evnt.data);}websocket.onclose = function(evnt) {console.log("onclose----", evnt.data);}$('#btn').on('click', function() {if(websocket.readyState == websocket.OPEN) {var msg = $('#id').val();//調用後台handleTextMessage方法websocket.send(msg);} else {alert("串連失敗!");}});$('#disconnection').on('click', function() {if(websocket.readyState == websocket.OPEN) {websocket.close();//websocket.onclose();console.log("關閉websocket串連成功");}});$('#connection').on('click', function() {if(websocket.readyState == websocket.CLOSED) {websocket.open();//websocket.onclose();console.log("開啟websocket串連成功");}});//監聽視窗關閉事件,當視窗關閉時,主動去關閉websocket串連,防止串連還沒斷開就關閉視窗,server端會拋異常。window.onbeforeunload = function() {websocket.close();}function uploadImgTest() {}function uploadImage(){//var uploadUrl = "http://localhost:8860/v1/uploadDownload/uploadImage";var uploadUrl = "http://192.168.9.123:8860/v1/uploadDownload/uploadImage";var downUrl = "http://192.168.9.123:8860/v1/uploadDownload/downloadImage"var pic = $('#upload_file')[0].files[0];        var fd = new FormData();        //fd.append('uploadFile', pic);        fd.append('file', pic);        $.ajax({            url:uploadUrl,            type:"post",            // Form資料            data: fd,            cache: false,            contentType: false,            processData: false,            success:function(data){            console.log("the data is : {}",data);            if(data.code == 0){            console.log("上傳成功後的檔案路徑為:"+data.data);            var img = $("<img />")            img.attr("src",downUrl+"?imageName="+data.data);            img.width("160px");            img.height("160px");            $("#imgp").append(img);            }                            }        });}</script></html>

上面的代碼有些和圖片的上傳和下載沒有關係,根據需要自己去掉,看圖片上傳和下載的核心代碼,需要引入jquery。

3,spring boot的屬性配置:

1,解決圖片上傳太大的問題:

spring: http:    multipart:       max-file-size: 100Mb   #檔案上傳大小        max-request-size: 200Mb  #最打請求大小
spring:  http:      multipart:        max-file-size: 100Mb   #檔案上傳大小        max-request-size: 200Mb  #最打請求大小

這是新版spring boot解決圖片或者檔案上傳太大的問題,老闆的不是這樣解決的。可以自己查資料

2,設定檔上傳儲存的位置:


#上傳位置
uploadDir: F:\mystudy\pic\

spring boot多檔案上傳:

核心代碼:

/**     * 多檔案上傳     * @param files     * @return     * @throws RuntimeException     */    @RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)    public JSONObject uploadFiles(@RequestParam(value = "file") MultipartFile[] files){        StringBuffer result = new StringBuffer();        try {            for (int i = 0; i < files.length; i++) {                if (files[i] != null) {                    //調用上傳方法                    String fileName = executeUpload(files[i]);                    result.append(fileName+";");                }            }        } catch (Exception e) {            e.printStackTrace();            JsonUtil.getFailJsonObject("檔案上傳失敗");        }        return JsonUtil.getSuccessJsonObject(result.toString());    }    /**     * 提取上傳方法為公用方法     * @param file     * @return     * @throws Exception     */    private String executeUpload(MultipartFile file)throws Exception{        //檔案尾碼名        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));        //上傳檔案名稱        String fileName = UUID.randomUUID()+suffix;        //服務端儲存的檔案對象        File serverFile = new File(uploadDir + fileName);        // 檢測是否存在目錄        if (!serverFile.getParentFile().exists()) {            serverFile.getParentFile().mkdirs();        }        //將上傳的檔案寫入到伺服器端檔案內        file.transferTo(serverFile);        return fileName;    }
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.