sprintboot 图片上传功能实现

sprintboot 图片上传功能实现

出现的问题:项目重启之后,图片访问404

原因:没有做静态资源虚拟路径映射
步骤:
1、首先将上传的图片进行处理,保存图片到本地磁盘的文件夹内

package com.github.alenfive.rocketapi.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ch.qos.logback.core.net.SyslogOutputStream;
import com.github.alenfive.rocketapi.entity.ResponseResult;
import org.apache.commons.collections4.bag.SynchronizedSortedBag;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;

/**
 * 照片上传工具类
 * @author admin
 *
 */
@Controller
@RequestMapping("/upload")
public class UploaderController extends BaseController{
    @ResponseBody
    @RequestMapping("/img")
    public void uploadPicture(@RequestParam(value="file",required=false)MultipartFile file,HttpServletRequest request,HttpServletResponse response){
        ResponseResult result = new ResponseResult();
        Map map = new HashMap();
        File targetFile=null;
        //返回存储路径
        String url="";
        int code=1;
        System.out.println(file);
        //获取文件名加后缀
        String fileName = file.getOriginalFilename();
        if(fileName != null && fileName != ""){
            //图片访问的URI
            String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() +"/upload/imgs/";
            //文件临时存储位置
            String path = request.getSession().getServletContext().getRealPath("") + "upload" + File.separator + "imgs";

            //文件后缀
            String fileSuffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            //新的文件名
            fileName = System.currentTimeMillis()+"_"+new Random().nextInt(1000) + fileSuffix;

            //先判断文件是否存在
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String fileAdd = sdf.format(new Date());
            //获取文件夹路径
            path = path + File.separator + fileAdd + File.separator;
            logger.info("path:{}",path);
            File file1 =new File(path);
            //如果文件夹不存在则创建
            if(!file1 .exists()  && !file1 .isDirectory()){
                file1 .mkdirs();
            }
            //将图片存入文件夹
            targetFile = new File(file1, fileName);
            try {
                //将上传的文件写到服务器上指定的文件。
                file.transferTo(targetFile);
                String projectPath = System.getProperty("user.dir");
                logger.info("projectPath:{}",projectPath);
                //文件复制
                String src = path + fileName;

//                String destDir = projectPath + File.separator +"src"+File.separator+"main"+ File.separator +"resources"+File.separator+"static"+ File.separator+"upload"+File.separator+"imgs" + File.separator + fileAdd + File.separator;
//                String destDir = "D:\\linshi\\img\\"+File.separator+"upload"+File.separator+"imgs" + File.separator + fileAdd + File.separator;
                String destDir = "/usr/local/zigbeeProject/resources/static/"+File.separator+"upload"+File.separator+"imgs" + File.separator + fileAdd + File.separator;
                System.out.println("destDir:"+destDir);
                copyFile(src,destDir,fileName);

                url= returnUrl + fileAdd + "/"+ fileName;
                code=0;
                result.setCode(code);
                result.setMessage("图片上传成功");
                map.put("name", fileName);
                map.put("url", url);

                result.setResult(map);
            } catch (Exception e) {
                e.printStackTrace();
                result.setMessage("系统异常,图片上传失败");
            }
        }
        writeJson(response, result);
    }

    /**
     * 文件复制
     * @param src
     * @param destDir
     * @param fileName
     * @throws IOException
     */
    public void copyFile(String src,String destDir,String fileName) throws IOException {
        FileInputStream in=new FileInputStream(src);
        File fileDir = new File(destDir);
        if(!fileDir.isDirectory()){
            fileDir.mkdirs();
        }
        File file = new File(fileDir,fileName);

        if(!file.exists()){
            file.createNewFile();
        }
        FileOutputStream out=new FileOutputStream(file);
        int c;
        byte buffer[]=new byte[1024];
        while((c=in.read(buffer))!=-1){
            for(int i=0;i

2、当访问网址时,将虚拟路径映射到磁盘文件夹内。(这样就算项目重启,图片依然可以访问得到)

package com.github.alenfive.rocketapi.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    // 配置虚拟路径映射访问
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
//        // 映射图片保存地址
        registry.addResourceHandler("/static/upload/imgs/**")
                .addResourceLocations("file:/usr/local/zigbeeProject/resources/static/upload/imgs/");
        registry.addResourceHandler("/upload/imgs/**")
                .addResourceLocations("file:/usr/local/zigbeeProject/resources/static/upload/imgs/");

//        // 映射图片保存地址
//        registry.addResourceHandler("/static/upload/imgs/**")
//                .addResourceLocations("file:D:\\linshi\\img\\\\upload\\imgs\\");
//        registry.addResourceHandler("/upload/imgs/**")
//                .addResourceLocations("file:D:\\linshi\\img\\\\upload\\imgs\\");
    }
}

你可能感兴趣的:(springboot)