图片上传到指定服务器(后台)
前台实现:需要引入jquery.form.js
$("#file1").change(function(){ $("#form1").ajaxSubmit(function(data){ $("#testImg1").attr("src",data.data.picUrl+data.data.imgfurl); }); });
/** * 手持上传 * @param file * @param request * @return * @throws Exception */ @RequestMapping("/uploadImgsc") @ResponseBody public ResultMap uploadImgsc(@RequestParam(value = "uploadFile", required = false) MultipartFile file ,HttpServletRequest request) throws Exception{ // String imgUrl = Constant.imageUrl+"/fastupload_w/fast/upload"; System.out.println("file:"+file); String imgUrl = "http://image.xxxx.com/fastupload_w/fast/upload" + ""; String imgfurl = ""; int maxSize = 5 * 1024 * 1024; // 5M // 获得文件类型(可以判断如果不是图片,禁止上传) File dest = uploadFileDest(file, request); //将内存中的文件写入磁盘 file.transferTo(dest); imgfurl = Upload.uploadFile(dest, imgUrl); if (imgfurl==null){ return ResultMap.error("上传失败"); } JSONObject img=JSONObject.parseObject(imgfurl); dest.delete(); logger.info("上传路径:"+imgfurl); JSONObject param=new JSONObject(); param.put("imgfurl",img.get("url")); param.put("picUrl","http://read.image.39tx.cc/" + ""); System.out.println("上传完毕"); return ResultMap.ok(param); } private File uploadFileDest(MultipartFile file, HttpServletRequest request) { //获取容器 再获取项目根目录 String pathRoot = request.getSession().getServletContext().getRealPath("/"); //网页中存在的Content-Type类型 String contentType = file.getContentType(); System.out.println("contentType:"+contentType); String uuid = UUID.randomUUID().toString().replaceAll("-", ""); //获取文件后缀名称 如:image/png String imageName = contentType.substring(contentType.indexOf("/") + 1); String path = "upload/" + uuid + "." + imageName; logger.info("存放本地路径:"+pathRoot + path); File dest = new File(pathRoot + path); if(!dest.exists()){ //获取父目录,在生成文件 dest.getParentFile().mkdirs(); } return dest; } /** * 上传文件到服务器 * * @param file * 需要上传的文件 * @param RequestURL * 请求的rul <a href='\"http://cccc.jpg\"' * target='\"_blank\"'>@return</a> 返回响应的内容 */ public static String uploadFile(File file, String RequestURL) { String result = null; String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成 String PREFIX = "--", LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; // 内容类型 try { URL url = new URL(RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIME_OUT); conn.setConnectTimeout(TIME_OUT); conn.setDoInput(true); // 允许输入流 conn.setDoOutput(true); // 允许输出流 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); // 请求方式 conn.setRequestProperty("Charset", CHARSET); // 设置编码 conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); if (file != null) { /** * 当文件不为空,把文件包装并且上传 */ DataOutputStream dos = new DataOutputStream( conn.getOutputStream()); StringBuffer sb = new StringBuffer(); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); /** * 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件 * filename是文件的名字,包含后缀名的 比如:abc.png */ sb.append("Content-Disposition: form-data; name=\"desc\"" + "" + "\n" + LINE_END + "zt" + LINE_END); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); sb.append("Content-Disposition: form-data; name=\"photo\"; filename=\"" + file.getName() + "\"" + LINE_END); sb.append("Content-Type: image/*; charset=" + CHARSET + LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes()); InputStream is = new FileInputStream(file); byte[] bytes = new byte[1024]; int len = 0; while ((len = is.read(bytes)) != -1) { dos.write(bytes, 0, len); } is.close(); dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END) .getBytes(); dos.write(end_data); dos.flush(); /** * 获取响应码 200=成功 当响应成功,获取响应的流 */ int res = conn.getResponseCode(); System.out.println("response code:" + res); // if(res==200) // { System.out.println("request success"); InputStream input = conn.getInputStream(); StringBuffer sb1 = new StringBuffer(); int ss; while ((ss = input.read()) != -1) { sb1.append((char) ss); } result = sb1.toString(); System.out.println("result : " + result); // } // else{ // Log.e(TAG, "request error"); // } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; }