关于文件上传的坑,tomcat一重启图片就消失
首先在tomcat的conf的server.xml中配置一个配置.
记得要找到Host标签。在这个标签里面添加
<Context path ="/File" docBase ="D:/File" debug ="0" privileged ="true"> </Context>
最终效果是这样的:
<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" /> --> <Context path ="/File" docBase ="D:/File" debug ="0" privileged ="true"> </Context> <!-- 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" /> </Host>
在后台用的时候就可以这样写
String productName = req.getParameter("productName"); String productDesc = req.getParameter("productDesc"); String productPrice = req.getParameter("productPrice"); Part cover = req.getPart("productImage"); Long da = new Date().getTime()/1000; String filePath = "/"+da+"_"+cover.getSubmittedFileName(); File file = new File("/File"); //这里是重点 String destPath = file.getAbsolutePath()+filePath; new File(destPath).getParentFile().mkdir(); cover.write(destPath); int categoryId = Integer.parseInt(req.getParameter("categoryId")); Product product = new Product(productName,productDesc,new BigDecimal(productPrice),filePath,categoryId); ProductService service = new ProductService(); service.insertProduct(product); resp.sendRedirect(req.getContextPath()+"/index");
上面我标记的地方就会去找D://File
idea里面在配置一个东西
在上面的HTTP port 右侧点上勾
就可以用在jsp使用了
<img id="image" src="/File${product.productImage}" style="width: 100px" >