java 服务器文件上传与下载

  1. 服务器下载互联网返回文件到本地服务器
//MediaUrl	String	原始媒体文件的 URL 地址。
String mediaUrl = "";
String url = mediaUrl+"?download_name="+name+"."+type;
int ec = FileDownload.downloadImage(url);
@Log
public class FileDownload {
    public static int downloadImage(String fileUrl ) {
        long l = 0L;
        String path = null;
        int ec = 0;
        if (fileUrl != null) {
            //下载时文件名称后缀
            String fileName = fileUrl.substring(fileUrl.lastIndexOf("=")+1);
            try {
                String dataStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
                //String uuidName = UUID.randomUUID().toString();
                // = "resources/"+dataStr+"/"+uuidName+fileName;
                // 准备文件夹,获取项目中upload文件夹的路径System.getProperty("user.dir")
                String parentDir = System.getProperty("user.dir")+File.separator+"upload"+File.separator+dataStr;
                //staticAndMksDir = Paths.get(ResourceUtils.getURL("classpath:").getPath(),"resources",dataStr).toString();
                log.info("下载文件链接:"+fileUrl+"位置:"+parentDir + File.separator + fileName);
                l=System.currentTimeMillis();
//                System.getProperties().list(System.out);
                HttpUtil.downloadFile(fileUrl, parentDir + File.separator + fileName);
                log.info("下载文件"+fileName+"共使用:"+(System.currentTimeMillis()-l)+"ms");
            } catch (Exception e) {
                log.info("下载文件"+fileName+"失败:");
                ec = 10001;
                e.printStackTrace();
            } finally {

            }
        }

        return ec;
    }
}
  1. 上传文件到其他服务器
		File file = new File(localFile);
        //restApiUrl
        PostMethod filePost = new PostMethod(restApiUrl+"/download");
        HttpClient client = new HttpClient();
        try {
        // 通过以下方法可以模拟页面参数提
        Part[] parts = { new FilePart("file", file) };

            filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
            client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
            int status = client.executeMethod(filePost);
            if (status == HttpStatus.SC_OK) {
                log.info("上传视频到内网成功"+localFile);
                return "";
            } else {
                log.info("上传视频到内网失败"+localFile);
                return "error";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return "error";
        } finally {
            filePost.releaseConnection();
        }
  1. 服务器1接到服务器2返回的文件流,返回到互联网
@GetMapping("/queryMedia/{mediaName}")
	public void queryMedia(@PathVariable("mediaName")  String mediaName,HttpServletResponse response) throws Exception {
		HttpRequestUtil.sendFileGet(ControllerConstant.INTRAURL+"tinyFile/"+mediaName, "",response);	
	}
 public static void sendFileGet(String requestUrl, String param,HttpServletResponse response) throws Exception  {
    	logger.info("发送get请求:"+requestUrl+"参数:"+param+"获取当前参数"+sysKey+sysCode);
        URL u = new URL(requestUrl);
        //注意:重点知识,此句判断用于信任所有的https请求
        /*if("https".equalsIgnoreCase(u.getProtocol())){
            //测试SslUtils
            SslUtils.ignoreSsl();
        }*/
        String result = "";
        BufferedReader in = null;
        BufferedWriter out = null;
        try {
            String urlString = requestUrl + "?" + param;
            URL url = new URL(urlString);
            // 打开和URL之间的连接
            URLConnection connection = url.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            
            connection.setRequestProperty("PFPJ-SourceSysKey", sysKey);
            connection.setRequestProperty("PFPJ-SourceSysCode", sysCode);
            if(gray) {
            	connection.setRequestProperty("white", "true");
            }
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            
            
            byte[] buffer = new byte[1024];
//			FileInputStream fis = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
	        try {

	            OutputStream os = response.getOutputStream();

	            int i = bis.read(buffer);
	            while (i != -1) {
	                os.write(buffer, 0, i);
	                i = bis.read(buffer);
	            }
	         } catch (IOException e) {
	 			// TODO Auto-generated catch block
	 			e.printStackTrace();
	 		} finally {
	             if (bis != null) {
	                 bis.close();
	             }
	         }
//            logger.info("发送get请求:"+requestUrl+"参数:"+param+"返回信息:"+result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
//        return result;
    }
  1. 上传所有格式的数据
@PostMapping("/upload/part")
	@ResponseBody
	public CommonResult uploadPart(Part file) {
		CommonResult comm = new CommonResult();
		String fileName = file.getSubmittedFileName();
		System.out.println(fileName);
//		String newName = System.currentTimeMillis()+"."+fileName.split(".")[1];
		try {
			file.write(fileName);
			comm.setMsg(beforeMediaUrl+fileName);
		}catch(Exception e) {
			log.info(e.toString());
			e.printStackTrace();
			comm.setMsg("上传失败");
		}
		return comm;
		
	}
@Component
public class TinyFileWebConfiguration implements WebMvcConfigurer {
	
	@Value("${spring.servlet.multipart.location}")
    private String filePath;
 
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
 
        // 注意如果filePath是写死在这里,一定不要忘记尾部的/或者\\,这样才能读取其目录下的文件
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/META-INF/resources/",
                "classpath:/resources/",
                "classpath:/static/",
                "classpath:/public/",
                "file:/" + filePath,
                "file:/home/psbcbj/corpwx/app/intranetfinancial-atlas/",
                "classpath:/webapp/");

    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值