项目中我们可能会使用到异步上传并且有时需要是异步的,那么Ajaxfileupload是一个不错的选择,最近刚 做了一个多文件上传到远程服务器,远程服务器提供接口,当远程服务器上传结束后返回一个文件的服务器地址。分享出来给有需要的参考 下,Ajaxfileupload默认是一次只能上传一个文件的,所以需要稍稍修改下他的源码就可以上传多个文件,这里就不多说,百度一下自然就知道。
<input type="file" id="playeraddress" name="playeraddress" /> <input type="file" id="cover" name="cover" /> //这里就是两个file id自己定义
$.ajaxFileUpload({ url : web_path+'upload/upload.do', secureuri : false, data : data,//需要传递的数据 json格式 fileElementId :['playeraddress','cover'], dataType : 'json', success : function(data) { //上传成功后的回调。 }, error : function(data) { } });
/** * * * @param request * @param response * @param audioItem * @return */ @RequestMapping(value = "/upload.do", method = { RequestMethod.POST }) @ResponseBody public String addMusic(HttpServletRequest request, HttpServletResponse response, AudioItem audioItem) { //这里无需理会,这只是 String uploadFileUrl = GlobalUtil .getValue("upload_audioItem_audio_url"); String uploadIconUrl = GlobalUtil.getValue("upload_audioItem_pic_url"); CommonsMultipartResolver resolver = new CommonsMultipartResolver( request.getServletContext()); if (resolver.isMultipart(request)) { MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; // 取得request中的所有文件名 Iterator<String> iter = multiRequest.getFileNames(); while (iter.hasNext()) { String fileName = iter.next(); // 取得上传文件 MultipartFile file = multiRequest.getFile(fileName); /** * 获取文件名 */ String originalFilename = file.getOriginalFilename(); if ("playeraddress".equals(fileName)&&!"".equals(originalFilename)) { try { //这里的upload方法就是以http post的方式上传文件的 稍后贴出 String url = BaseService.upload(uploadFileUrl, file.getOriginalFilename(), file.getInputStream()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if ("cover".equals(fileName)&&!"".equals(originalFilename)){ try { String icon = BaseService.upload(uploadIconUrl, file.getOriginalFilename(), file.getInputStream()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //这里需要注意 使用Ajaxfileupload需要使用以下方式返回结果 回调不了success 方法 response.setContentType("text/html"); try { response.getWriter().write("ok"); } catch (IOException e) { e.printStackTrace(); } } return null; }
//最后一步了 public static String upload(String httpurl, String fileName, InputStream inputStream) { String result = ""; try { //这里看你的网络环境 按需设置代理 正常都不需要理会 if (true) { System.setProperty("http.proxyHost", BaseService.PROXY_IP); System.setProperty("http.proxyPort", BaseService.PROXY_PORT); } String BOUNDARY = "---------7d4a6d158c9"; // 定义数据分隔线 URL url = new URL(httpurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); OutputStream out = new DataOutputStream(conn.getOutputStream()); byte[] end_data = ("/r/n--" + BOUNDARY + "--/r/n").getBytes();// 定义最后数据分隔线 StringBuilder sb = new StringBuilder(); sb.append("--"); sb.append(BOUNDARY); sb.append("/r/n"); sb.append("Content-Disposition: form-data;name=/"file" + 1 + "/";filename=/"" + fileName + "/"/r/n"); sb.append("Content-Type:application/octet-stream/r/n/r/n"); byte[] data = sb.toString().getBytes(); out.write(data); DataInputStream in = new DataInputStream(inputStream); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } out.write("/r/n".getBytes()); // 多个文件时,二个文件之间加入这个 in.close(); out.write(end_data); out.flush(); out.close(); // 定义BufferedReader输入流来读取URL的响应 BufferedReader reader = new BufferedReader(new InputStreamReader( conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { result+=line; } } catch (Exception e) { System.out.println("发送POST请求出现异常!" + e); } return new JSONObject(result).getString("url"); } // 到这就结束了!希望能帮到你。
来自:http://my.oschina.net/pingdy/blog/361833
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/8020.html