图片文件上传
一、文件上传条件:
1、依赖表单,请求方式为post, enctype="multipart/form-data"
2、表单中有file类型的input
二、提交文件上传的表单,不需要页面跳转,用jquery.form.js插件。以ajax方式提交表单
1 function submitUpload(){ 2 var option = { 3 url:path+"/upload/uploadPic.do",//上传的url 4 dataType:"text",//回调值的数据类型 5 success:function(responseText){ 6 var jsonObject = $.parseJSON(responseText); 7 //图片回显 8 $("#imgsImgSrc").attr("src",jsonObject.realPath); 9 //图片相对路径用于数据库保存 10 $("#imgs").val(jsonObject.relativePath); 11 //页面保存上次访问路径 12 $("#lastRealPath").val(jsonObject.realPath); 13 }, 14 error:function(){ 15 alert("系统错误"); 16 } 17 }; 18 //使用ajax方式提交表单 19 $("#form111").ajaxSubmit(option); 20 }
三、在springMVC配置文件中设置
<!-- 复杂类型文件上传 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxInMemorySize" value="1024000"/> </bean>
四、文件服务器设置为只读
1 <init-param> 2 <param-name>readonly</param-name> 3 <param-value>false</param-value> 4 </init-param>
五、创建文件上传方法
@Controller @RequestMapping("/upload") public class EbUploadController { @RequestMapping("/uploadPic.do") public void uploadPic(HttpServletRequest request,PrintWriter pw,String lastRealPath) throws IOException { MultipartHttpServletRequest req = (MultipartHttpServletRequest) request; //获得input类型的name属性 Iterator<String> inputNames = req.getFileNames(); String inputName = inputNames.next(); //获得文件 MultipartFile file = req.getFile(inputName); //将文件转化成字节数组 byte[] fileBytes = file.getBytes(); //定义文件名 String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()); Random random = new Random(); for(int i=0;i<3;i++) { fileName = fileName + random.nextInt(10); } //获得原始文件名 String oriName = file.getOriginalFilename(); //获得后缀名 String suffix = oriName.substring(oriName.lastIndexOf(".")); String realPath = ECPSUtils.readProp("upload_file_path")+"/upload/"+fileName + suffix; String relativePath = "/upload/" + fileName + suffix; //不同主机文件上传,创建jersey客户端 Client client = Client.create(); //判断比较上次文件路径是否为空,如果不为空,则需要先删除上次图片 if(StringUtils.isNotBlank(lastRealPath)) { WebResource wr = client.resource(lastRealPath); wr.delete(); } //指定上传的绝对路径 WebResource wr = client.resource(realPath); //文件上传 wr.put(fileBytes); //回传绝对路径与相对路径 JSONObject jo = new JSONObject(); jo.accumulate("realPath", realPath); jo.accumulate("relativePath", relativePath); String responseText = jo.toString(); pw.print(responseText); } }