springboot 上传下载图片

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

上传多张图片:(此处是用来配合 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 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, 这样可以加载到非工程目录下的图片文件.

转载于:https://my.oschina.net/zcqshine/blog/1529073

你可能感兴趣的:(springboot 上传下载图片)