前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >springboot 上传下载图片

springboot 上传下载图片

作者头像
zcqshine
发布2018-05-11 16:06:12
2.7K0
发布2018-05-11 16:06:12
举报
文章被收录于专栏:zcqshine's blog

上传多张图片:(此处是用来配合 wangeditor用的. 当然, 稍作修改, 也可以用作他用)

代码语言:javascript
复制
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 "";
    }
}

图片显示:

代码语言:javascript
复制
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, 这样可以加载到非工程目录下的图片文件.

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档