restapi:上传文件接口开发

调用别人提供的url,进行文件上传接口开发:

@ResponseBody
	@RequestMapping(value = "/uploadPaasRes", method = RequestMethod.POST)
	public Map<String, Object> uploadPaasRes(String resId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String flagCode="";
		String flagMsg="";
		try {
			// 保存可见范围,并返回中文字符串,
			Page<CmRespakg> condition = new Page<CmRespakg>();
			condition.setOffset(0);
			condition.setPageSize(10000);
			//查询资产对应的文件包
			List<CmRespakg> cmRespakgList = cmRespakgService.selectListByResId(resId,condition);
			if("".equals(resId) || cmRespakgList.size()==0){
				resultMap.put("code", "0");
				resultMap.put("msg", "该资产无相关资产包,无法上传至PaaS平台!");
				return resultMap;
			}
		
			String uploadConfig = PropertiesUtil.classPath + "paasUpload.properties";
			String queryUrl = PropertiesUtil.getByKey(uploadConfig, "queryUrl", "");
			URL restURL = new URL(queryUrl);
		    BufferedReader br;
			try {
				//调用PaaS查询API
				HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
				br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

				String line;
				StringBuilder sb = new StringBuilder();
				while((line = br.readLine()) != null ){
				    sb.append(line);
				}
				String reqBody = sb.toString();
				JSONObject json = new JSONObject(reqBody);
				String harborprojectuid=(String) json.get("harborprojectuid");
				String projectuid=(String) json.get("projectuid");
				String serviceuid=(String) json.get("serviceuid");
				
				//调用上传接口url
				HttpURLConnection conne;
				try {
					String uploadUrl = PropertiesUtil.getByKey(uploadConfig, "uploadUrl", "");
					uploadUrl+="projects/"+projectuid+"/services/"+serviceuid+"/harbor-projects/"+harborprojectuid+"/upload";
					URL restServiceURL = new URL(uploadUrl);
					String boundaryString = PaasUploadUtil.getBoundary();
					//多文件处理(遍历资产信息,对于上传多个文件,要进行多次请求才可)

					for(int i=0;i<cmRespakgList.size();i++) {
						System.out.println("----resid----"+resId);
						System.out.println("----path----"+cmRespakgList.get(i).getPath());
						//多次请求
						conne = (HttpURLConnection) restServiceURL.openConnection();
						conne.setDoOutput(true);
						conne.setUseCaches(false);
						conne.setRequestMethod("POST");
						/* conne.setConnectTimeout(CONNECT_TIME_OUT);
						conne.setReadTimeout(READ_OUT_TIME);*/
						conne.setRequestProperty("accept", "*/*");
						conne.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString);
						conne.setRequestProperty("connection", "Keep-Alive");
						conne.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
						
						DataOutputStream obos = new DataOutputStream(conne.getOutputStream());
						
						//普通参数
						String tag=String.valueOf(new Date().getTime())+"tag";
						String namestr=cmRespakgList.get(i).getName().substring(0, cmRespakgList.get(i).getName().indexOf("."));
						String repository="software/"+namestr;
						System.out.println("-----repository-----"+repository);
						Map<String, String> textMap=new HashMap<String, String>();
						textMap.put("repository", repository);
						textMap.put("tag", tag);

						HashMap<String, byte[]> fileMap=new HashMap<String, byte[]>();

// (fileToMultipartFile:该文件转换方法在windows情况下可用,项目部署到linux服务器上时该方法使用会有问题)	
//fileMap.put("file",PaasUploadUtil.getBytesFromFile(PaasUploadUtil.fileToMultipartFile(new File("/home/ftpuser/"+cmRespakgList.get(i).getPath()))));

//获取linux服务器上的文件地址			
fileMap.put("file",PaasUploadUtil.getBytesFromFile(PaasUploadUtil.getMulFileByPath("/home/ftpuser/"+cmRespakgList.get(i).getPath())));

//本地测试,获取数据库中对应的本地文件地址						
//fileMap.put("file",PaasUploadUtil.getBytesFromFile(PaasUploadUtil.getMulFileByPath(cmRespakgList.get(i).getPath())));

						Iterator iter = textMap.entrySet().iterator();
						while(iter.hasNext()){
							Map.Entry<String, String> entry = (Map.Entry) iter.next();
							String key = entry.getKey();
							String value = entry.getValue();
							obos.writeBytes("--" + boundaryString + "\r\n");
							obos.writeBytes("Content-Disposition: form-data; name=\"" + key
									+ "\"\r\n");
							obos.writeBytes("\r\n");
							obos.write((value+ "\r\n").getBytes());
						}
						if(fileMap != null && fileMap.size() > 0){
							Iterator fileIter = fileMap.entrySet().iterator();
							while(fileIter.hasNext()){
								Map.Entry<String, byte[]> fileEntry = (Map.Entry<String, byte[]>) fileIter.next();
								obos.writeBytes("--" + boundaryString + "\r\n");
								obos.writeBytes("Content-Disposition: form-data; name=\"" + fileEntry.getKey()
								+ "\"; filename=\"" + PaasUploadUtil.encode(" ") + "\"\r\n");
								obos.writeBytes("\r\n");
								obos.write(fileEntry.getValue());
								obos.writeBytes("\r\n");
							}
						}
						obos.writeBytes("--" + boundaryString + "--" + "\r\n");
						obos.writeBytes("\r\n");
						
						obos.flush();
						obos.close();
						InputStream ins = null;
						int code = conne.getResponseCode();
						System.out.println("----code-----:"+code);
						
						if(code == 200){
							ins = conne.getInputStream();
						}else{
							ins = conne.getErrorStream();
						}
						ByteArrayOutputStream baos = new ByteArrayOutputStream();
						byte[] buff = new byte[4096];
						int len;
						while((len = ins.read(buff)) != -1){
							baos.write(buff, 0, len);
						}
						byte[] bytes = baos.toByteArray();
						ins.close();
						String reponseStr = new String(bytes);;
						
						JSONObject responseJson = new JSONObject(reponseStr);
						System.out.println("=======responseJson======"+responseJson);
						String message=(String) responseJson.get("message");
						
						if("500".equals(String.valueOf(code))) {
							flagCode+="0,";
							int num=i+1;
							flagMsg+="该资产第"+num+"资产包"+message+",";
							continue;
						}
						String status=(String) responseJson.get("status");
						if(!"success".equals(status)) {
							flagCode+="0,";
						}else {
							flagCode+="1,";
						}
						int num=i+1;
						flagMsg+="该资产第"+num+"资产包"+message+",";
						
					}

				} catch (Exception e) {
					e.printStackTrace();
					resultMap.put("code", "0");
					resultMap.put("msg", "paas上传接口调用失败");
				}
		        
			} catch (Exception e) {
				e.printStackTrace();
				resultMap.put("code", "0");
				resultMap.put("msg", "查询paas信息APi调用失败");
			}

		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("code", "0");
			resultMap.put("msg", "上传失败");
		}
		if(!"".equals(flagCode) && !"".equals(flagMsg)) {
			resultMap.put("code", flagCode);
			resultMap.put("msg", flagMsg);
			return resultMap;
		}
		resultMap.put("code", "1");
		resultMap.put("msg", "文件上传至PaaS平台成功");
	    
		return resultMap;
	}

帮助类

package com.neunn.ruma.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Random;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

public class PaasUploadUtil {
	
	public static String getBoundary() {
	        StringBuilder sb = new StringBuilder();
	        Random random = new Random();
	        for(int i = 0; i < 32; ++i) {
	            sb.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-".charAt(random.nextInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".length())));
	        }
	        return sb.toString();
	 }
	 
	/**
	 * MultipartFile 转 File
	 * @param file
	 * @throws Exception
	 */
	public static void multipartFileToFile( @RequestParam MultipartFile file ) throws Exception {

	    File toFile = null;
	    if(file.equals("")||file.getSize()<=0){
	        file = null;
	    }else {
	            InputStream ins = null;
	            ins = file.getInputStream();
	            toFile = new File(file.getOriginalFilename());
	            inputStreamToFile(ins, toFile);
	            ins.close();
	    }

	}
	
	public static void inputStreamToFile(InputStream ins, File file) {
	    try {
	        OutputStream os = new FileOutputStream(file);
	        int bytesRead = 0;
	        byte[] buffer = new byte[8192];
	        while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
	            os.write(buffer, 0, bytesRead);
	        }
	        os.close();
	        ins.close();
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	}
	
	
	/**
	  * File 转 MultipartFile   (该文件转换方法在windows情况下可用,项目部署到linux服务器上时该方法使用会有问题)
	  * @param file
	  * @throws Exception
	  */
	 public static MultipartFile fileToMultipartFile(File file) throws Exception {
		 MultipartFile multipartFile = null;
		 try {
				FileInputStream input = new FileInputStream(file);
				multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input));
		 } catch (Exception e) {
				e.printStackTrace();
		 }
		 return multipartFile;
	 }
	 
	 /**
	  * File 转 MultipartFile2(该文件转换方法兼容windows和linux,推荐使用)
	  * @param picPath
	  * @return
	  */
	 public static MultipartFile getMulFileByPath(String picPath) {  
	        FileItem fileItem = createFileItem(picPath);  
	        MultipartFile mfile = new CommonsMultipartFile(fileItem);  
	        return mfile;  
	 }  
	 
	 public static FileItem createFileItem(String filePath) {
		 	File file=new File(filePath);
		    FileItemFactory factory = new DiskFileItemFactory(16, null);
		    String textFieldName = "file";
		    int num = filePath.lastIndexOf(".");
		    String extFile = filePath.substring(num);
		    FileItem item = factory.createItem(textFieldName, "text/plain", true, file.getName());
		    File newfile = new File(filePath);
		    int bytesRead = 0;
		    byte[] buffer = new byte[8192];
		    try {
		        FileInputStream fis = new FileInputStream(newfile);
		        OutputStream os = item.getOutputStream();
		        while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
		            os.write(buffer, 0, bytesRead);
		        }
		        os.close();
		        fis.close();
		    } catch (IOException e) {
		        e.printStackTrace();
		    }
		    return item;
	 }

	 
	 //编码格式
	 public static String encode(String value) throws Exception{
	        return URLEncoder.encode(value, "UTF-8");
	 }
	 
	 //文件转成byte流
	 public static byte[] getBytesFromFile(MultipartFile f) {
		 File mfCovFile = null;
		 try {
		 	 mfCovFile = new File(f.getOriginalFilename());
		 	 FileUtils.copyInputStreamToFile(f.getInputStream(), mfCovFile);
		 } catch (IOException e) {
		 	e.printStackTrace();
		 }

		 if (f == null) {
		 	return null;
		 }
		 try {
		 	 FileInputStream stream = new FileInputStream(mfCovFile);
		 	 ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
		 	 byte[] b = new byte[1000];
		 	 int n;
		 	 while ((n = stream.read(b)) != -1)
		 	 out.write(b, 0, n);
		 	 stream.close();
		 	 out.close();
		 	 return out.toByteArray();
		 } catch (IOException e) {
			 	e.printStackTrace();
		 }
		 return null;
	    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44465068/article/details/89280671