12.02工作总结(文件上传与下载)

1. 文件上传到远端服务器

@RequestMapping("/uploadfile")
	public void uploadfile(HttpServletRequest request,HttpServletResponse response, 
			@RequestParam MultipartFile file) {		
		if(file.getSize()==0) {
			JsonUtil out = new JsonUtil(request, response);
			out.outObjString("上传失败,不能上传空文件");
			return;
		}
		
	    String appid= request.getParameter("appid");
		
		//如果文件不为空,写入上传路径 
		String filename = ""; 			
		// 上传文件名
		filename = file.getOriginalFilename();
        // 新文件名
        String newFileName = UUID.randomUUID().toString() + "." + filename.substring(filename.lastIndexOf(".") + 1);
		//根据文件名进行获取文件对象
		CommonsMultipartFile mf = (CommonsMultipartFile) file;
		String suffix = mf.getOriginalFilename().substring(mf.getOriginalFilename().lastIndexOf("."));
		String fullPath="";
		try {
			//将文件对象转换为字节
			byte[] fileBytes = mf.getBytes();
			//创建jesy服务器,进行跨服务器上传
			Client client = Client.create();
			//绝对路径
			fullPath += FileUtil2.r1mysql+newFileName;
			WebResource wr = client.resource(fullPath);
			//上传
			wr.put(fileBytes);
			int flg = systemappservice.updatedownurl(appid,fullPath);
			JsonUtil out = new JsonUtil(request, response);
			out.outObjString("上传成功");
		} catch (Exception e) {
			JsonUtil out = new JsonUtil(request, response);
			out.outObjString("上传失败");
			e.printStackTrace();
		}
		
	}
public class FileUtil2 {
	//院校信息图片
	public static String yxxxPicture = "http://118.190.156.108:8888/linfenshi_upload_file/zhms/yxxx/";
	//医院信息图片
	public static String yyxxPicture = "http://118.190.156.108:8888/linfenshi_upload_file/zhms/yyxx/";
	//分类信息图片通知公告
	public static String flxxPicture = "http://118.190.156.108:8888/linfenshi_upload_file/zhms/flxx/";
	//栏目管理
	public static String lmglPicture = "http://118.190.156.108:8888/linfenshi_upload_file/zhms/lmgl/";
	//红名单黑名单
	public static String mdPicture = "http://118.190.156.108:8888/linfenshi_upload_file/zhms/md/";
	//富文本
	public static String fwbPicture = "http://118.190.156.108:8888/linfenshi_upload_file/zhms/fwb/";

	//远程文件服务器
	public static String baseFilePath = "http://118.190.156.108:8888/linfenshi_upload_file/zhms/";
	
	//远程文件服务器
	public static String r1mysql = "http://118.190.156.108:8888/linfenshi_upload_file/r1mysql/";
}

在这里插入图片描述

'<a class="button button-little bg-red" href="javascript:;" onclick="submitapp(\''+obj.appid+'\')">'+
											'<span class="icon-trash-o"></span> 上传'+
										'</a>&nbsp;&nbsp;'+
function submitapp(appid) {
	
	$("#upfile").click();
	$("#appid").val(appid);
}
$(function() {
	var sysid = getQueryString("sysid");
	$("#sysid").val(sysid);
	pageHtm(1,MSysPath+"/system/management/systemapp/systemapppage","cfom");
	
	$("#upfile").change(function() { //上传
		
		console.log($(this).val());
		if ($(this).val() == null || $(this).val() == "")
			return;
		url = $(this).val().split("\\");
		$("#attc_name").val(url[url.length - 1]);
		var options = {
			url  : MSysPath+$("#fileform").attr("action") ,
			success : function(result) {			
				obj = result.data;
				parent.layer.msg(obj);
				pageHtm(1,MSysPath+"/system/management/systemapp/systemapppage","cfom");
			}
		};
		
		$("#fileform").ajaxSubmit(options);
	})
});
<form id="fileform" action="/system/management/systemapp/uploadfile.action"
		                     method="post" enctype="multipart/form-data">
      <input type="hidden" id="attc_name" name="attc_name">
      <input type="hidden" id="appid" name="appid">
      <input id="upfile" name="file" type="file" style="display: none;" />
 </form>
	           

需要两个jar包依赖

<dependency>
		<groupId>org.glassfish.jersey.core</groupId>
		<artifactId>jersey-common</artifactId>
		<version>2.22.2</version>
</dependency>
  		
<dependency>
         <groupId>com.sun.jersey</groupId>
		 <artifactId>jersey-client</artifactId>
		 <version>1.9.1</version>
 </dependency>

2. 文件上传到本地服务器

在这里插入图片描述
在这里插入图片描述
jsp:

<td width="20%">
	<a id="tjfj" href="#" class="ch_cls sel_btn" onclick="clickFileInput();">添加附件</a>
</td>
<form id="fileform" action="<%=root%>/uploadSwAttr.action"  method="post" enctype="multipart/form-data">
 	<input type="hidden" id="attc_name" name="attc_name">
 	<input type="hidden" id="sw_id" name="sw_id"> 
 	<input type="hidden" id="orgid" name="orgid" value="<%=orgid%>"> 
	<input type="hidden" id="busi_id" name="busi_id">
	<input type="hidden" id="busi_type" name="busi_type" value="0"> 
    <input type="hidden" id="ext1" name="ext1">
	<input type="hidden" id="ext2" name="ext2"> 
	<input type="hidden" id="ext3"  name="ext3">
	<input type="hidden" id="op_user" name="op_user"  value="<%=username%>">
	<input type="hidden" id="op_userid"  name="op_userid" value="<%=userid%>">
	<input id="upfile"  name="file" type="file" style="display: none;" />
</form>
//触发点击文件选择
function clickFileInput() {
	$("#upfile").click();
}
$("#upfile").change(function() { //添加附件   这个需要在$(function(){ });里面
		console.log($(this).val());
		if ($(this).val() == null || $(this).val() == "")  //判断是否为空
			return;
		url = $(this).val().split("\\");   
		$("#attc_name").val(url[url.length - 1]);  //获取文件名称(包括文件格式)
		var options = {
			success : function(result) {
				obj = result.data;
				if(obj == "上传成功"){
					$("#tjfj").text("继续添加");
				}
				layer.msg(obj);
                
				attclist();
			}
		};

		$("#fileform").ajaxSubmit(options);
		$(this).val("");
	})
@RequestMapping(value = "/uploadSwAttr", method = RequestMethod.POST)
	public void uploadSwAttr(@RequestParam MultipartFile file, HttpServletRequest request,
			HttpServletResponse response) {
		if(file.getSize()==0) {
			JsonUtil out = new JsonUtil(request, response);
			out.outObjString("上传失败,不能上传空文件");
			return;
		}
		SwAttr attr=new SwAttr();
		attr.setAttc_name(request.getParameter("attc_name"));
		attr.setSw_id(request.getParameter("sw_id"));
		attr.setOrgid(request.getParameter("orgid"));
		attr.setBusi_id(request.getParameter("busi_id"));
		attr.setBusi_type(request.getParameter("busi_type"));
		attr.setExt1(request.getParameter("ext1"));
		attr.setExt2(request.getParameter("ext2"));
		attr.setExt3(request.getParameter("ext3"));
		attr.setOp_user(request.getParameter("op_user"));
		attr.setOp_userid(request.getParameter("op_userid"));
	
		attr.setAttc_type(file.getContentType());
//		System.out.println(file.getContentType());
		attr.setAttc_no(UUID.randomUUID().toString());
		response.setContentType("text/html; charset=UTF-8");
		// 取到存储上传文件的路径
		String root = request.getContextPath();
		
		attr.setOp_time(sdf.format(new Date()));
		
		String id=attrService.insert(attr);// 插入数据先获取id
		attr.setAttc_id(id);
		attr.setAttc_path("/disk/"+ attr.getAttc_id() + attr.getAttc_name());
		attrService.update(attr);
		String path = filepath + attr.getAttc_id() + attr.getAttc_name();
		try {
			File f = new File(path);
			file.transferTo(f);// 保存文件
			JsonUtil out = new JsonUtil(request, response);
			out.outObjString("上传成功");
		} catch (Exception e) {
			JsonUtil out = new JsonUtil(request, response);
			out.outObjString("上传失败");
		}
	}
private String filepath = this.getClass().getClassLoader().getResource("").getPath().substring(1)
			.replaceAll("/WEB-INF/classes/", "") + File.separator + "disk" + File.separator;

3. 文件下载

controller层

@RequestMapping("/downloadSwAttr")
	public void downloadSwAttr(HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("text/html; charset=UTF-8");
		String id = request.getParameter("id");
		SwAttr attr = attrService.getbyId(id);
		String patr = filepath + attr.getAttc_id() + attr.getAttc_name();
//		System.out.println(patr);
		Long fileLength = new File(patr).length();// 文件的长度
//		System.out.println("patr:"+patr);
//		System.out.println("fileLength:"+fileLength);
		if (fileLength != 0) {// 将本地文件写入到返回response的输出流
			UploadUtil.webDownload(request,response,fileLength,patr,attr.getAttc_name());
		}
	}

UploadUtil.java

package com.***.base.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;

public class UploadUtil {
	private static String CHARSET = "UTF-8";

	/**
	 * 
	 * @param 参数
	 * @param 服务器文件地址
	 * @param 服务器地址
	 * @return
	 **/
	public static String startUploadService(Map<String, String> params, String file_url, String server_url) {
		try {
			// 开启上传队列
			File file = null;
			if (!file_url.equals("")) {
				file = new File(file_url);
			}
			CloseableHttpClient httpClient = HttpClients.createDefault();

			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectTimeout(200000).setSocketTimeout(200000000)
					.build();

			HttpPost httppost = new HttpPost(server_url);
			httppost.setConfig(requestConfig);

			MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
			multipartEntityBuilder.addBinaryBody("file", file);
			multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
			multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

			if (params != null && !params.isEmpty()) {
				for (Entry<String, String> entry : params.entrySet()) {
					multipartEntityBuilder.addTextBody(entry.getKey(), entry.getValue());
				}
			}
			HttpEntity httpEntity = multipartEntityBuilder.build();
			httppost.setEntity(httpEntity);

			HttpResponse response = httpClient.execute(httppost);
			HttpEntity resEntity = response.getEntity();
			if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
				EntityUtils.toString(response.getEntity(), CHARSET);
				return "{\"code\":\"4000\", \"msg\":\"URL请求失败\", \"result\":\'" 
						+ response.getStatusLine().toString()
						+ "\'}";
			}
			String result = (resEntity == null) ? null : EntityUtils.toString(resEntity, CHARSET);
			return result;
		} catch (UnsupportedEncodingException e) {
			return "{\"code\":\"4002\", \"msg\":\"URL请求失败\", \"result\":\'UnsupportedEncodingException:"
					+ e.getMessage() + "\'}";
		} catch (ClientProtocolException e) {
//			System.out.println(e.getMessage());
			return "{\"code\":\"4003\", \"msg\":\"URL请求失败\", \"result\":\'ClientProtocolException:" 
					+ e.getMessage()
					+ "\'}";
		} catch (IOException e) {
//			System.out.println(e.getMessage());
			return "{\"code\":\"4001\", \"msg\":\"URL请求失败\", \"result\":\'IOException:" 
					+ e.getMessage() + "\'}";
		}
	}
	/**
	 * web下载文件把本地文件写入响应数据流
	 * @param request
	 * @param response
	 * @param fileLength 文件长度
	 * @param patr 文件路径
	 */
	public static void webDownload(HttpServletRequest request, HttpServletResponse response,Long fileLength,String patr,String filename) {
		response.reset();
		response.setContentType("application/octet-stream;charset=utf-8");
		try {
			response.setHeader("Content-disposition",
					"attachment; filename=" + new String(filename.getBytes("utf-8"), "ISO8859-1"));
			response.setHeader("Content-Length", String.valueOf(fileLength));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(patr);
			bis = new BufferedInputStream(fis);
			// 输出流
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesread;
			// 写文件
			while (-1 != (bytesread = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesread);
			}
			fis.close();
			bis.close();
			bos.close();
		} catch (Exception e) {
			JsonUtil out = new JsonUtil(request, response);
			out.outObjString("下载失败");
		}
	}
	public static byte[] download(Map<String, String> params, String url) {
		byte[] in2b = null;
		try {
			CloseableHttpClient client = HttpClients.createDefault();
			if (params != null && !params.isEmpty()) {
				boolean first = false;
				for (Entry<String, String> entry : params.entrySet()) {// 循环添加参数
					if (!first) {
						url = url + "?" + entry.getKey() + "=" + entry.getValue();
						first = true;
					} else {
						url = url + "&" + entry.getKey() + "=" + entry.getValue();
					}
				}
			}

			HttpGet httpget = new HttpGet(url);
			httpget.addHeader("Content-type", "text/html; charset=UTF-8");
			HttpResponse response = client.execute(httpget);

			HttpEntity entity = response.getEntity();

			InputStream is = entity.getContent();

			// File file = new File(filepath);
			// file.getParentFile().mkdirs();
			// FileOutputStream fileout = new FileOutputStream(file);
			/**
			 * 根据实际运行效果 设置缓冲区大小
			 */
			// byte[] buffer = new byte[1024];
			// int ch = 0;
			// while ((ch = is.read(buffer)) != -1) {
			// fileout.write(buffer, 0, ch);
			// }

			ByteArrayOutputStream output = new ByteArrayOutputStream();

			byte[] buffer = new byte[4096];
			int n = 0;

			while (-1 != (n = is.read(buffer))) {
				output.write(buffer, 0, n);
			}

			in2b = output.toByteArray();

			is.close();
			output.flush();
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return in2b;
	}

	public static byte[] File2byte(String filePath) {
		byte[] buffer = null;
		try {
			File file = new File(filePath);
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			fis.close();
			bos.close();
			buffer = bos.toByteArray();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer;
	}

	public static void byte2File(byte[] buf, String filePath, String fileName) {
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		File file = null;
		try {
			File dir = new File(filePath);
			if (!dir.exists() && dir.isDirectory()) {
				dir.mkdirs();
			}
			file = new File(filePath + File.separator + fileName);
			fos = new FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			bos.write(buf);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	// 解析上传
	public static InputStream parseUpload(HttpServletRequest request, Map<String, String> params) {
		InputStream is = null;
		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 设置上传文件的大小限制为10M
			factory.setSizeThreshold(1024 * 10240);
			List items = upload.parseRequest(request);
			Iterator iter = items.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (!item.isFormField()) {
					// item.getInputStream() 获取上传文件的输入流
					is = item.getInputStream();
				} else {
					String paramName = item.getFieldName();
					String paramValue = item.getString();
					paramValue = new String(paramValue.getBytes("ISO-8859-1"), "UTF-8");
					params.put(paramName, paramValue);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return is;
	}
}

4. 删除上传的文件

@RequestMapping(value = "/deleteAttr", method = RequestMethod.GET)
	public void deleteAttr(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		SwAttr attr = attrService.getbyId(id);
		attrService.delete(id);   //删除数据库中的记录
		File file = new File(filepath + attr.getAttc_id() + attr.getAttc_name());
		file.delete();
		// 删除上传的文件
	}

5. JsonUtil.java

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class JsonUtil {
	
	public JsonUtil(HttpServletRequest request,HttpServletResponse response){
		this.request = request;
		this.response = response;
	}

	/** 当前HttpServletRequest */
	protected HttpServletRequest request;
	/** 当前HttpServletResponse */
	protected HttpServletResponse response;
	
	protected PrintWriter writer;

	public PrintWriter getWriter() {
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return writer ;
	}

	public void setWriter(PrintWriter writer) {
		this.writer = writer;
	}
	
	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}
	
	// JSON
	private void setJsonHeader(){
		HttpServletResponse r =getResponse();
		r.setContentType("application/json;charset=UTF-8");
		r.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
		r.setHeader("Pragma", "no-cache"); // HTTP 1.0.
		r.setDateHeader("Expires", 0); // Proxies.
	}

	/**
	 * 警告:请不要直接使用此函数,防止产生缓存问题
	 * 请考虑使用outObjString
	**/
	public void outString(String str) {
		try {
			PrintWriter out = getResponse().getWriter();
			out.print(str);
			//System.out.println(str);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void outJson(String str) {
		setJsonHeader();
		outString(str);
	}

	@SuppressWarnings("rawtypes")
	public void outListString(List list) {
		if(list == null) list = new ArrayList();
		setJsonHeader();
		String jsonString = "{\"success\":true,\"total\":" + list.size() + ",\"data\":" + new Gson().toJson(list) + "}";
		outString(jsonString);
	}
	
	@SuppressWarnings("rawtypes")
	public void outDelOrInListString(List tripList,List list) {
		if(list == null) list = new ArrayList();
		setJsonHeader();
		String jsonString = "{\"success\":true,\"total\":" + list.size()
				+ ",\"data\":" + new Gson().toJson(tripList) + ",\"deleteTrip\":"
				+ new Gson().toJson(list) + "}";
		outString(jsonString);
	}
	
	@SuppressWarnings("rawtypes")
	public void outComboString(List list) {
		setJsonHeader();
		String jsonString = null;
		if(list==null||list.isEmpty()){
			jsonString = "{total:" + 0 + ",root:}";
		}else{
		   jsonString = "{total:" + list.size() + ",root:"
				+ new Gson().toJson(list) + "}";
		}

		outString(jsonString);
		
	}

	@SuppressWarnings("rawtypes")
	public void outListStringToJSON(List list) {
		setJsonHeader();
		String jsonString = "{\"total\":" + list.size() + ",\"root\":" + new Gson().toJson(list) + "}";
		outString(jsonString);
	}
	
	@SuppressWarnings("rawtypes")
	public void outQueryDate(List list) {
		setJsonHeader();
		String jsonString = "{\"success\":true,\"data\":" + new Gson().toJson(list) + "}";
//		System.out.println(jsonString);
		outString(jsonString);
	}

	public void outObjString(Object obj) {
		setJsonHeader();
		String jsonString = "{\"success\":true,\"data\":" + new Gson().toJson(obj) + "}";
		outString(jsonString);
	}

	@SuppressWarnings("rawtypes")
	public void outTreeJsonList(List list) {
		getResponse().setContentType("application/xml;charset=UTF-8");
		outString(new Gson().toJson(list));
//		System.out.println(new Gson().toJson(list));
	}
	
	@SuppressWarnings("rawtypes")
	public void outMapToJson(Map map) {
		setJsonHeader();
		String jsonString = "{\"success\":true,\"data\":" + new Gson().toJson(map) + "}";
//		System.out.println(jsonString);
		outString(jsonString);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值