ajaxFileUpload实现异步上传到阿里云服务器

ajaxFileUpload是一款基于jquery的ajax上传方式的文件上传插件,提供了异步上传的文件的功能,也可以支持多文件上传功能。

在OSS中,用户操作的基本数据单元是文件Object(文件)。OSS Java SDK提供了丰富的文件上传接口,供开发者调用。

step1:首先导入所需jar和相关js(博主所用)

    <script src="jquery-1.9.1.js" type="text/javascript"></script>  这里要注意先后顺序(多嘴一下)
    <script src="ajaxfileupload.js" type="text/javascript"></script>

com.springsource.org.apache.commons.fileupload-1.3.1.jar
com.springsource.org.apache.commons.io-2.4.0.jar
aliyun-sdk-oss-2.7.0	

step2:因为这里使用了springmvc框架,所以需要进行上传配置(spring相关jar不做解释)

<bean id="exceptionResolver" class="com.fh.resolver.MyExceptionResolver"></bean>
	  <bean id="multipartResolver"   class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >   
		  <property name="maxUploadSize">    
	          <value>104857600</value>    
	       </property>   
	        <property name="maxInMemorySize">    
	            <value>4096</value>    
	        </property>   
	         <property name="defaultEncoding">    
	            <value>utf-8</value>    
	        </property> 
    </bean>  

step3:ajaxFileUpload使用

参数说明:

1、url           服务器上传接口地址,这个就不用说了吧。  
2,fileElementId      input控件的ID
3,secureuri        是否启用安全提交,默认为false。
4,dataType        服务器返回的数据类型。可以为xml,script,json,html。
5,success        成功回调
6,error          失败回调
7,data           自定义参数
8, type            传参方式(post和get)


<body>
     <input id="fileone" type="file" name="fileone">
    <input type="button" name="file" class="file-button" value="上传文件">
<script type="text/javascript">
function upload() {
    $.ajaxFileUpload
    ({
       url: 'url', //用于文件上传的服务器端请求地址
       type:'post',
       secureuri: false, //是否需要安全协议,一般设置为false
       fileElementId: "fileone", //对应input的ID
       data:{ 携带的数据
       },
       dataType: 'json', //返回值类型一般设置为json
       success: function (data, status)  //服务器成功响应处理函数
        {
           if(data>0){
              alert("上传成功");
			  console.log(data.filePath);//可以进行文件的回显操作(在这里就不做说明)
           }else{
              alert("上传失败");
             
           }
        }
 
    })
}
</script>
</body>

step4:Oss实现上传

public class OssUtil {
	// 登录阿里云申请账号,开通oss图片存储服务; 
	// 登录控制台oss新建bucket(存储空间也叫容器)(注意命名规范,设置公共读写); 
	// 获取key和secret 
	// 初始化一个OSSClient, OSSClient是与OSS服务交互的客户端,SDK的OSS操作都是通过OSSClient完成的。
	public static final OSSClient getOSSClient() {
		return new OSSClient("key", "secret", "域名"); 
	}

	// 通过文件名判断并获取OSS服务文件上传时文件的contentType
	public static final String getContentType(String fileName) {
		String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
		if ("bmp".equalsIgnoreCase(fileExtension)) {
			return "image/bmp";
		}
		if ("gif".equalsIgnoreCase(fileExtension)) {
			return "image/gif";
		}
		if (("jpeg".equalsIgnoreCase(fileExtension)) || ("jpg".equalsIgnoreCase(fileExtension))
				|| ("png".equalsIgnoreCase(fileExtension))) {
			return "image/jpeg";
		}
		if ("html".equalsIgnoreCase(fileExtension)) {
			return "text/html";
		}
		if ("txt".equalsIgnoreCase(fileExtension)) {
			return "text/plain";
		}
		if ("vsd".equalsIgnoreCase(fileExtension)) {
			return "application/vnd.visio";
		}
		if (("ppt".equalsIgnoreCase(fileExtension)) || ("pptx".equalsIgnoreCase(fileExtension))) {
			return "application/vnd.ms-powerpoint";
		}
		if (("doc".equalsIgnoreCase(fileExtension)) || ("docx".equalsIgnoreCase(fileExtension))) {
			return "application/msword";
		}
		if ("xml".equalsIgnoreCase(fileExtension)) {
			return "text/xml";
		}
		return "text/html";
	}
	// 上传文件
	public static final String uploadInfo(InputStream is, String fileName) // 上传,并返回在文件oss上的存储路径
	{
		OSSClient client = getOSSClient();
		String resultUrl = "";
			try {
				Random random = new Random(); // 定义一个随机数
				long a = System.currentTimeMillis();
				String current = String.valueOf(a);
				String randomName = random.nextInt(9000) + 1000 + current;// 产生随机数组合
				String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);// 得到文件后缀
				fileName = randomName + "." + prefix;// 生成最终文件名
				ObjectMetadata metadata = new ObjectMetadata();// ObjectMetaData是用户对该object的描述
				metadata.setCacheControl("no-cache");
				metadata.setHeader("Pragma", "no-cache");
				metadata.setContentEncoding("utf-8");
				metadata.setContentType(getContentType(fileName));
				Calendar cal = Calendar.getInstance();
				int year = cal.get(1);
				int month = cal.get(2) + 1;
				String diskName = year + "/" + month + "/";
				client.putObject("存储空间的名称", diskName + fileName, is, metadata);
				resultUrl = "https://存储空间的名称.oss-cn-shenzhen.aliyuncs.com/" + diskName + fileName;
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				client.shutdown();
			}
			return resultUrl;
		}
}


step5:编写controller

	@RequestMapping(value = "/前台ajax的url", method = RequestMethod.POST)
	public void uploadfujian(@RequestParam("fileone") final CommonsMultipartFile uploadFile, final Model model,
			final HttpServletRequest request, final HttpServletResponse response) throws Exception {
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		Map<String, Object> result = new HashMap<String, Object>();
			// 调用服务处理文件上传逻辑
			try {
				int length = uploadFile.getBytes().length;
				if ((length / 1000) > 5120) {
					response.getWriter().println("{'info':'上传失败,大小超出限制!'}");
					return;
				}
				if (length > 0) {
					String FileName = uploadFile.getOriginalFilename();// 获取原wenjia名称
					InputStream in = uploadFile.getInputStream();// 转成流文件
					String returnUrl = OssUtil.uploadInfo(in, FileName);
					result.put("filePath", returnUrl);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		String json = new Gson().toJson(result, new TypeToken<Map<String, Object>>() {
		}.getType());
		response.getWriter().print(json);
	}







 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值