springboot 上傳下載圖片

上傳多張圖片:(此處是用來配合 wangeditor用的. 當然, 稍作修改, 也可以用作他用)


import com.fxtcn.gov.faq.util.JSONUtil;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上傳
 * @Description: Created by zcqshine on 2017/8/24.
 */
@RestController
@RequestMapping("admin/upload")
public class UploadController extends BaseController {
    @Value("${upload.file.path}")
    private String file_path;    //文件上傳的根目錄

   
    @RequestMapping("image")
    public String upload(@RequestParam("imageFiles") MultipartFile[] imageFiles) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("errno", 0);

        try {
                if (imageFiles != null && imageFiles.length > 0){
                    String[] strings = new String[imageFiles.length];
                    int i = 0;
                    for (MultipartFile imageFile : imageFiles) {
                        String fileName = imageFile.getOriginalFilename();
                        //判斷是否有文件且是否爲圖片
                        if (!Strings.isNullOrEmpty(fileName) && isImageFile(fileName)){
                            //創建輸出文件對象
                            String saveFilename = UUID.randomUUID().toString() + getFileType(fileName);
                            File outFile = new File(file_path + saveFilename);
                            imageFile.transferTo(outFile);
                            strings[i] = "/download/" + saveFilename;
                            i++;
                        }
                    }
                    map.put("data", strings);
                } else {
                    map.put("errno", 1);
                    map.put("data", null);
                }
        } catch (Exception e) {
            map.put("errno", 1);
            map.put("data", null);
            throw e;
        }

        return JSONUtil.toJsonString(map);
    }

    /**
     * 判斷文件是否爲圖片
     * @param fileName
     * @return
     */
    private boolean isImageFile(String fileName){
        String[] img_type = new String[]{".jpg",".jpeg", ".png", ".gif", ".bmp"};
        if (Strings.isNullOrEmpty(fileName)){
            return false;
        }
        fileName = fileName.toLowerCase();

        for (String type : img_type){
            if (fileName.endsWith(type)){
                return true;
            }
        }

        return false;
    }

    /**
     * 獲取文件後綴名
     * @param fileName
     * @return
     */
    private String getFileType(String fileName) {
        if(fileName!=null && fileName.indexOf(".")>=0) {
            return fileName.substring(fileName.lastIndexOf("."), fileName.length());
        }
        return "";
    }
}

圖片顯示:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.nio.file.Paths;

/**
 * @Description: Created by zcqshine on 2017/8/25.
 */
@RestController
@RequestMapping("download")
public class DownloadController {

    private final ResourceLoader resourceLoader;

    @Value("${upload.file.path}")
    private String file_path;

    @Autowired
    public DownloadController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @SystemExceptionLog(description = "下載圖片")
    @RequestMapping(method = RequestMethod.GET, value = "/{filename:.+}")
    public ResponseEntity<?> getFile(@PathVariable String filename){
        try {
            String path = Paths.get(file_path, filename).toString();
            Resource resource = resourceLoader.getResource("file:" + path);
            return ResponseEntity.ok(resource);
        } catch (Exception e) {
            throw e;
        }
    }
}

在圖片顯示中用到了 ResourceLoader, 這樣可以加載到非工程目錄下的圖片文件.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章