Javawebspring boot

springboot jar包运行文件上传及显示

2018-08-19  本文已影响18人  大大大浣熊

文件上传是在web开发中所遇到的比较常见的需求了,常见的文件上传有几种

@Configuration
public class WebAppConfig implements WebMvcConfigurer {
    @Value("${my.upload.imgPath}")
    private String path;
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String staticMapping="/image/**";
        String localDirectory = "file:"+path;
        registry.addResourceHandler(staticMapping).addResourceLocations(localDirectory);
        WebMvcConfigurer.super.addResourceHandlers(registry);
    }
}

就这么几行代码,其中localDirectory变量是外部文件夹,文件需要上传到该文件夹中去,staticMapping就是映射的静态资源请求路径了。
比如说

localDirectory="/usr/file/image";(如果是windows下就"D://file/image")
staticMapping="/image/**"

文件上传到localDirectory中后直接通过http://localhost:8080/image/xx.png即可拿到文件。
下面把controller也一起贴出来吧

@Controller
@RequestMapping(value = "index")
public class IndexController {
    @Value("${my.upload.imgPath}")
    private String imgPath;
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
    public String upload(HttpServletRequest request){
        //上传文件时可能会带普通的参数,这样可以直接拿到
        String name = request.getParameter("name");
        //可能会有多个文件同时上传
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        BufferedOutputStream stream = null;
        for (MultipartFile f : files) {
            if (f.isEmpty()){
                continue;
            }
            try {
                byte[] b = f.getBytes();
                String fileName = f.getOriginalFilename();
                // String path = "src/main/resources/uploadFile/";
//                String path = imgPath+fileName;
                String path = "/Users/halo/Documents/HtmlProject/"+fileName;
                stream = new BufferedOutputStream(new FileOutputStream(new File(path)));
                stream.write(b);
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "success";

    }

    @RequestMapping("hello")
    public String indexController(Model model){
        model.addAttribute("imgsrc", "/image/34.jpg");
        return "index";
    }
}

demo地址https://download.csdn.net/download/luo_dream/10614232

上一篇 下一篇

猜你喜欢

热点阅读