SpringMVC上传图片存到指定位置,并能够使用Tomcat访问

来源:互联网 发布:什么是数据库营销 编辑:程序博客网 时间:2024/05/18 09:18





首先

服务端接收的文件 保存到指定目录

@ResponseBody@RequestMapping(value = "/upload", method = RequestMethod.POST)public ResponseData upload(@RequestParam(value = "file") MultipartFile file) {    String address = "";    try {        System.out.println("fileName:" + file.getOriginalFilename());        address = uploadFile(file, "G:\\Images\\");    } catch (IOException e) {        e.printStackTrace();    }    return new ResponseData(address, "222", 200);}

文件保存

    public String uploadFile(MultipartFile partFile, String rootPath) throws IllegalStateException, IOException {        if (partFile != null && partFile.getOriginalFilename() != null && partFile.getOriginalFilename().length() > 0) {            Calendar cal = Calendar.getInstance();            int month = cal.get(Calendar.MONTH) + 1;            int year = cal.get(Calendar.YEAR);            String filePath = rootPath + year + "年" + month + "月/";            File dir = new File(filePath);            if (!dir.isDirectory())                dir.mkdir();            String fileOriginalName = partFile.getOriginalFilename();            String newFileName = UUID.randomUUID() + fileOriginalName.substring(fileOriginalName.lastIndexOf("."));//            String newFileName = fileOriginalName+ fileOriginalName.substring(fileOriginalName.lastIndexOf("."));            File file = new File(filePath + newFileName);            //文件写入磁盘            partFile.transferTo(file);            //返回存储的相对路径+文件名称            return "" + year + "年" + month + "月/" + newFileName;        } else            return null;    }

 Tomcat 配置 Host 制定的doc目录

G:\Images
和访问的虚拟路径
/img
<Host name="localhost"  appBase="webapps"            unpackWARs="true" autoDeploy="true">        <!-- SingleSignOn valve, share authentication between web applications             Documentation at: /docs/config/valve.html -->        <!--        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />        -->        <!-- Access log processes all example.             Documentation at: /docs/config/valve.html             Note: The pattern used is equivalent to using pattern="common" -->        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"               prefix="localhost_access_log." suffix=".txt"               pattern="%h %l %u %t "%r" %s %b" /><Context path="/img" docBase="G:\Images" />      </Host>


测试能够上传成功,但是Tomcat一直访问不到

百度一番 终于解决 


勾选上 就能访问了



访问地址:http://localhost:8080/img/2017%E5%B9%B48%E6%9C%88/51bb1e18-8d21-46f9-8fbf-cec56af8f5fa.jpg

物理地址:G:\Images\2017年8月\51bb1e18-8d21-46f9-8fbf-cec56af8f5fa.jpg


参考:http://bbs.csdn.net/topics/391972284

https://my.oschina.net/pingdy/blog/199592



阅读全文
0 0
原创粉丝点击