java上传文件到远程服务器七牛云



我们在前面已经学习如何把文件上传到远程服务器中,这里的远程服务器一般是我们自己的Linux服务器。

如下:


 java上传文件到远程服务器(一)---HttpURLConnection方式


java上传文件到远程服务器(二)---HttpClient方式


如果说 不想自己搭建 静态资源Linux服务器的话,现在有很多免费的静态资源云服务可以使用。


本文记录java上传文件到远程服务器七牛云中。


关于七牛云的介绍和注册使用读者可以自己查看官网。

https://www.qiniu.com/


使用七牛云作为图片等静态资源存储的话 查看 对象存储功能。


在实现上传文件到七牛云之前需要准备三个东西。


String accessKey = "your access key"; // 个人中心密钥管理中的AK
String secretKey = "your secret key"; //个人中心密钥管理中的SK
String bucket = "your bucket name"; // 对象存储空间名(如果有多个空间,自己想要上传到哪个空间则使用哪个空间名)

如下图:






我们在之前的文章中已经在SpringMVC基础框架的基础上应用了BootStrap的后台框架,在此基础上记录HttpURLConnection上传文件到远程服务器。

应用bootstrap模板


基础项目源码下载地址为:

SpringMVC+Shiro+MongoDB+BootStrap基础框架


我们在基础项目中已经做好了首页index的访问。
现在就在index.jsp页面和index的路由Controller上做修改,上传文件到七牛云。



index.jsp代码为:

<%@ include file="./include/header.jsp"%>
        

HttpURLConnection HttpURLConnection


  
<%@ include file="./include/footer.jsp"%>



需要引入qiniuyun的jar包。


我这里使用maven,则在pom.xml中加入:

	
			com.qiniu
			qiniu-java-sdk
			7.2.0
		



IndexController.java代码如下:

package com.test.web.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

/**
 * IndexController
 * 
 * 
 */
@Controller
public class IndexController {


	@RequestMapping("/")
	public String index(Model model) throws IOException {

		return "/index";
	}

	
	 @RequestMapping("/upload")  
	    public String upload(HttpServletRequest request) throws Exception {  
	        // 判断enctype属性是否为multipart/form-data  
	        boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
	        if (!isMultipart)  
	            throw new IllegalArgumentException(  
	                    "上传内容不是有效的multipart/form-data类型.");  
	  
	        // Create a factory for disk-based file items  
	        DiskFileItemFactory factory = new DiskFileItemFactory();  
	  
	        // Create a new file upload handler  
	        ServletFileUpload upload = new ServletFileUpload(factory);  
	  
	        // Parse the request  
	        List items = upload.parseRequest(request);  
	  
	        Iterator iter = items.iterator();  
	        while (iter.hasNext()) {  
	            FileItem item = (FileItem) iter.next();  
	  
	            if (item.isFormField()) {  
	                // 如果是普通表单字段  
	                String name = item.getFieldName();  
	                String value = item.getString();  
	                // ...  
	            } else {  
	                // 如果是文件字段  
	                String fieldName = item.getFieldName();  
	                String fileName = item.getName();  
	                String contentType = item.getContentType();  
	                boolean isInMemory = item.isInMemory();  
	                long sizeInBytes = item.getSize();  
	                // ...  
	  
	                // 上传到远程服务器  
	                HashMap files = new HashMap();  
	                files.put(fileName, item);  
	                uploadToQiNiuYun(files);  
	            }  
	        }  
	        return "redirect:/";  
	    }


	private void uploadToQiNiuYun(HashMap files) throws IOException {
		//构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone2());
		//...其他参数参考类注释
//		华东	Zone.zone0()
//		华北	Zone.zone1()
//		华南	Zone.zone2()
//		北美	Zone.zoneNa0()

		UploadManager uploadManager = new UploadManager(cfg);
		//...生成上传凭证,然后准备上传
		String accessKey = "nPVt7d0gCZP9CdLVjw6o";//这里请替换成自己的AK
		String secretKey = "p-GkW8RS4Y0_EffU";//这里请替换成自己的SK
		String bucket = "shouxiang";//这里请替换成自己的bucket--空间名

		//默认不指定key的情况下,以文件内容的hash值作为文件名
		String key = null;

		
		 Iterator iter = files.entrySet().iterator();  
         int i=0;  
         while (iter.hasNext()) {  
             i++;  
             Map.Entry entry = (Map.Entry) iter.next();  
             String fileName = (String) entry.getKey();  
             FileItem val = (FileItem) entry.getValue();
             InputStream inputStream=val.getInputStream();
             ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); 
             byte[] buff = new byte[600]; //buff用于存放循环读取的临时数据 
             int rc = 0; 
             while ((rc = inputStream.read(buff, 0, 100)) > 0) { 
             swapStream.write(buff, 0, rc); 
             } 
             byte[] uploadBytes  = swapStream.toByteArray(); //uploadBytes 为转换之后的结果 
             Auth auth = Auth.create(accessKey, secretKey);
			String upToken = auth.uploadToken(bucket);
			try {
			    Response response = uploadManager.put(uploadBytes, key, upToken);
			    //解析上传成功的结果
			    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			    System.out.println(putRet.key);
			    System.out.println(putRet.hash);
			} catch (QiniuException ex) {
			    Response r = ex.response;
			    System.err.println(r.toString());
			    try {
			        System.err.println(r.bodyString());
			    } catch (QiniuException ex2) {
			        //ignore
			    }
			}
         }
		
		
	
		
	}  
}


上传成功后这里会输出 文件的hash名。这个hash名就是文件名。我们找到空间的外链域名,在浏览器中使用  外链域名/文件名  即可访问到图片:








更多七牛云的java上传用法请参考SDK:

https://developer.qiniu.com/kodo/sdk/1239/java#upload-flow




你可能感兴趣的:(web,java,web模块积累)