文件的上传、下载

package com.rl.ecps.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import net.sf.json.JSONObject;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.rl.ecps.utils.ECPSUtils;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;

/**
 * 图片、文件上传
 * 
 * @author zhaojd
 *
 */
@Controller
@RequestMapping("/upload")
public class EbUploadController {

	/**
	 * 文件上传方式一
	 * 		关键点,上传到图片服务器;通过jersey辅助
	 * 		缺陷:
	 * 			没有检查目录,没有去创建一层文件夹来提高IO
	 * @param imgsFile
	 * @throws IOException
	 */
	@RequestMapping("/uploadPic.do")
	public void uploadPic(@RequestParam("imgsFile") MultipartFile imgsFile, PrintWriter pw) throws IOException {
		
		// 图片名称的生成策略
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String format = simpleDateFormat.format(new Date());
		Random random = new Random();
		for (int i = 0; i < 3; i++) {
			format += random.nextInt(10);
		}
		// 获取图片的后缀名
		String ext = FilenameUtils.getExtension(imgsFile.getOriginalFilename());
		String fileName = format + "." + ext;
		// 上传文件的绝对路径
		String url = ECPSUtils.readProp("file_path") + "/upload/" + fileName;
		// 上传文件的相对路径 用于保存在数据库
		String path = "/upload/"+ fileName;

		// 图片上传到另外一台服务器,需要jersey辅助
		Client client = new Client();
		// 设置请求路径
		WebResource resource = client.resource(url);
		// 获取文件的字节数据
		byte[] fileByteArray = imgsFile.getBytes();
		resource.put(fileByteArray);
		JSONObject jo = new JSONObject();
		jo.put("url", url);
		jo.put("path", path);
		pw.write(jo.toString());
	}

	/**
	 * 文件上传方式二
	 * 		缺陷:
	 * 		      开始获取文件的方式繁琐,且存在方式一的问题,仅供参考思路
	 * 
	 * @param request
	 * @param out
	 * @param lastPath
	 * @throws IOException
	 */
	// @RequestMapping("/uploadPic.do")
	// public void uploadPic(HttpServletRequest request, PrintWriter out, String lastPath) throws IOException{
	// //强制转换request
	// MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
	// //获得文件
	// Iterator<String> iter = mr.getFileNames();
	// String fileInputName = iter.next();
	// MultipartFile mf = mr.getFile(fileInputName);
	// //获得文件的字节数组
	// byte[] byteArr = mf.getBytes();
	// String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
	// Random random = new Random();
	// for(int i = 0 ; i < 3; i++){
	//     fileName = fileName + random.nextInt(10);
	// }
	// //获得原始文件名
	// String oriFileName = mf.getOriginalFilename();
	// String suffix = oriFileName.substring(oriFileName.lastIndexOf("."));
	// //获得文件服务器的主机地址
	// String filePath = ECPSUtils.readProp("file_path");
	// //获得上传文件的绝对路径
	// String realPath = filePath + "/upload/"+fileName + suffix;
	// String relativePath = "/upload/"+fileName + suffix;
	// Client client = Client.create();
	// if(StringUtils.isNotBlank(lastPath)){
	// WebResource wr1 = client.resource(lastPath);
	//     wr1.delete();
	// }
	// //创建Jersey客户端
	// WebResource wr = client.resource(realPath);
	// wr.put(byteArr);
	// //ajax返回多个值的时候要使用JSON
	// JSONObject jo = new JSONObject();
	// jo.accumulate("realPath", realPath);
	// jo.accumulate("relativePath", relativePath);
	// //{"realPath":"http://.....", "relativePath":"/upload/..."}
	// String result = jo.toString();
	// out.write(result);
//  }

	
	/**
	 * 文件上传方式三
	 * 		上传文件到同一服务器下的某个目录中,进行了目录检查及根据日期创建一层目录来提高IO
	 */
//	public String upload(MultipartFile helpFile) {
//		// 获得上传文件的保存路径    fileBase写在配置文件中的一个linux路径,UPLOAD_PATH="/help_doc/" 这样一个值;
//		String savePath = fileBase + UPLOAD_PATH; 
//		// 检查目录
//		File uploadDir = new File(savePath);
//		if (!uploadDir.exists() || !uploadDir.isDirectory()) {
//			uploadDir.mkdirs();
//		}
//		// 创建文件夹
//		SimpleDateFormat sdf = new SimpleDateFormat(CommonHelper.FORMAT_YYYYMMDD);
//		String ymd = sdf.format(new Date());
//		savePath += ymd + "/";
//		File dirFile = new File(savePath);
//		if (!dirFile.exists())
//			dirFile.mkdirs();
//		// 获取原始文件名
//		String originalFileName = helpFile.getOriginalFilename();
//		// 获取到文件的扩展名
//		String fileExt = originalFileName.substring(originalFileName.lastIndexOf(".")).toLowerCase();
//		// 新的文件名 当前时间值 + 三位int型随机数
//		String newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
//		Random random = new Random();
//		for (int i = 0; i < 3; i++) {
//			newFileName += random.nextInt(10);
//		}
//		newFileName += fileExt;
//		// 上传文件的相对路径
//		String relativePath = UPLOAD_PATH + ymd + "/" + newFileName;
//		File uploadedFile = new File(savePath, newFileName);
//		try {
//			helpFile.transferTo(uploadedFile);
//		} catch (IOException e) {
//			throw new RuntimeException(" ");
//		}
//		return relativePath;
//	}
//
//	/**
//	 * 文件下载
//	 */
//	@Override
//	@Transactional
//	public void downloadFile(String path, String docNameAddExt, HttpServletResponse response, HttpServletRequest request) {
//		FileInputStream fos = null;
//		ServletOutputStream sos = null;
//		try {
//			response.setContentType("multipart/form-data");
//			response.setHeader("Content-Disposition", "attachment; filename=" + new String(docNameAddExt.getBytes("gbk"), "iso-8859-1"));
//			fos = new FileInputStream(new File(fileBase + path));
//			sos = response.getOutputStream();
//			int read = 0;
//			byte b[] = new byte[1024 * 1024 * 1];// 1M
//			while ((read = fos.read(b)) != -1) {
//				sos.write(b, 0, read);// 每次写1M
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//			try {
//				if (sos != null) {
//					sos.close();
//				}
//				if (fos != null) {
//					fos.close();
//				}
//			} catch (IOException e) {
//				throw new RuntimeException("");
//			}
//		}
//	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值