上传下载文件的实现,记录一下

在springmvc 上传下载文件。
1.引用jar包,一般使用commons-fileupload-1.2.2.jar,commons-io-1.4.jar
2.在springmvc-context.xml配置编码格式大小等。具体代码如下

<bean id="multipartResolver" 
	    class="com.iss.itreasury.common.utils.PreMultipartResolver">  
	    <!-- 默认编码 -->
	    <property name="defaultEncoding" value="utf-8" />  
	    <!-- 文件大小最大值 -->
	    <property name="maxUploadSize" value="10485760000" />  
	    <!-- 内存中的最大值 -->
	    <property name="maxInMemorySize" value="40960" />
	    <!-- url中带有FileUploadServlet的http请求就不会被multipartResolver先解析--> 
	    <property name="excludeUrls" value="/web/withFileUpload"/>
</bean>

3.建立一个controller类,这个拦截器类,上传代码的时候先来到这个地方,再去实际的你上传代码的实际地方
例如:拦截器类为DownLoadFileController.java

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.iss.ebank.cpf.util.ConfigConstant;
import com.iss.ebank.cpf.util.FileDeal;
import com.iss.ebank.cpf.util.NameRef;
import com.iss.ebank.draft.discount.entity.FileMessageInfo;
import com.iss.ebank.draft.discount.service.FileMessageService;
@Controller
public class DownLoadFileController {
	@Autowired
	public FileMessageService fileMessageService;
	
	//private String uploadFolder = ConfigConstant.getConfig("drafts.fileUpload");
	private String uploadFolder = "/appshare/drafts/files";
	
	//*文件下载,只要传递文件的hashcode,就能从后台下载*
	@RequestMapping(value="/web/fileDownLoad.web")
	public void downloadFile(HttpServletResponse response,String hashCode){
		//通过hashCode查找文件位置
		if(hashCode==null || "".equals(hashCode.trim())){
			//传入的参数不对
			logger.error("没有传入需要下载的文件hashCode");
			return;
		}
		FileMessageInfo fileInfo = fileMessageService.findFileByCode(hashCode);
		if(fileInfo==null||fileInfo.getId()<=0){
			//文件不存在
			getUserContext().setInfoMessage("下载的文件不存在!");
			logger.error("没有查询到文件!hashCode=["+hashCode+"]");
			return;
		}
		//logger.info("查询到的文件信息为["+JSON.toJSONString(fileInfo)+"]");
		String filePath = fileInfo.getSfileUrl();
		String fileName = fileInfo.getSshowName();
		long downloadedLength = fileInfo.getNlength();
		try {
			fileName = URLEncoder.encode(fileName, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		//设置返回头
		response.reset();  
	    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");  
	    response.addHeader("Content-Length", "" + downloadedLength);  
	    response.setContentType("application/octet-stream;charset=UTF-8");  
		
		//读取文件,写入response的输出流
	    
	    try {
	        //打开本地文件流
	        InputStream inputStream = new FileInputStream(filePath);
	        //激活下载操作
	        OutputStream os = response.getOutputStream();

	        //循环写入输出流
	        byte[] b = new byte[2048];
	        int length;
	        while ((length = inputStream.read(b)) > 0) {
	            os.write(b, 0, length);
	            downloadedLength += b.length;
	        }

	        // 这里主要关闭。
	        os.close();
	        inputStream.close();
	    } catch (Exception e){
	        e.printStackTrace();
	    }
	}
	//上传文件的方法。
	@RequestMapping(value="/web/withFileUpload.web",method=RequestMethod.POST)
	public ModelAndView fileUpload(@RequestParam(value="sforUrl") String sforUrl,@RequestParam(required=false)  MultipartFile[] myfiles
			,@RequestParam(value="stype") String stype,HttpServletRequest request,HttpServletResponse response){
		
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("content-type", "text/html;charset=UTF-8");
		
		String url = "";
		if(sforUrl==null||sforUrl.trim().equals("")||stype==null||!(stype.equals("web")||stype.equals("do")||stype.equals("json")||stype.equals("jsonp"))){
			//没有可供转发的路径
			url = "/heads/pageHead";
			getUserContext().setInfoMessage("提交了非法路径!");
			return new ModelAndView(url);
		}
		url = "forward:/"+sforUrl+"."+stype;
		url = url.replaceAll("_", "/");
		ModelAndView mv = new ModelAndView(url);
		List<FileMessageInfo> uploadFiles = new ArrayList<FileMessageInfo>();
		try {
			if(myfiles!=null){
				for(MultipartFile file:myfiles){
					if(file.isEmpty()){
						logger.info("没有上传文件");
					}else{
						logger.info("文件长度: " + file.getSize());
						logger.info("文件类型: " + file.getContentType());
						logger.info("文件名称: " + file.getName());
						logger.info("文件原名: " + file.getOriginalFilename());
						
						FileMessageInfo info = new FileMessageInfo();
						info.setId(NameRef.getSeq_dp_fileAttach());
						info.setNlength(file.getSize());
						
						String fileName = file.getOriginalFilename();
						if(fileName!=null){
							int tt = fileName.lastIndexOf(".");
							if(tt>0){
								info.setSfileType(fileName.substring(tt+1));
							}else{
								info.setSfileType("");
							}
						}
						
						info.setShashcode(UUID.randomUUID().toString());
						info.setSoriName(file.getOriginalFilename());
						String sshowName = file.getOriginalFilename();
						info.setSshowName(sshowName);
						String folder = uploadFolder;
						if(folder==null||folder.trim().equals("")){
							folder = File.separatorChar + "opt";
						}
						if(!folder.endsWith(File.separatorChar+"")){
							folder = folder + File.separatorChar;
						}
						
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						folder = folder + sdf.format(new Date()) + File.separatorChar;
						
						String desFileName = "";
						if(info.getSfileType()!=null && !"".equals(info.getSfileType().trim())){
							info.setSfileUrl(folder+info.getShashcode()+"."+info.getSfileType());
							desFileName = info.getShashcode()+"."+info.getSfileType();
						}else{
							//原来的文件里面没有传入文件类型
							info.setSfileUrl(folder+info.getShashcode());
							desFileName = info.getShashcode();
						}
						
						
						logger.info("开始上传文件");
						try {
							boolean result = FileDeal.saveFile(file.getInputStream(),folder, desFileName);
							if(result){
								logger.info("文件["+info.getSoriName()+"]上传成功,存放于位置["+info.getSfileUrl()+"]");
								//电票附件表插入
								fileMessageService.addFileMessage(info);
								uploadFiles.add(info);
							}
						} catch (Exception e) {
							e.printStackTrace();
							logger.error("文件["+info.getSoriName()+"]上传失败,失败原因["+e.getMessage()+"]");
							logger.info("文件["+info.getSoriName()+"]上传失败,失败原因["+e.getMessage()+"]");
						}
					}
				}
			}else{
				logger.info("没有上传文件");
			}
			request.setAttribute("_uploadFiles", uploadFiles);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return mv;
	}
	

}
public static boolean saveFile(InputStream inputStream, String folderPath,String fileName) throws Exception {
		File folder = new File(folderPath);
		if(!folder.exists()){
			folder.mkdirs();
		}
		String filePath = folder.getAbsolutePath() + File.separatorChar + fileName;
		return saveFile(inputStream,filePath);
	}

4.具体上传的controller的方法

	//上传-链接
	@RequestMapping(value="/honour/web/addAttach.web", method=RequestMethod.POST)
	public String addFilePagelink(HttpServletRequest request, HttpServletResponse response, Model model, Writer writer) throws Exception {
		List<FileMessageInfo> uploadFiles=(List<FileMessageInfo>)request.getAttribute("_uploadFiles");
		long napplyid=-1;
		String istrTemp="";
		istrTemp = request.getParameter("napplyid");
        if( istrTemp != null && istrTemp.length() > 0 )
        {
        	napplyid =Long.parseLong(istrTemp.trim()) ;
        }
        
		for(FileMessageInfo file:uploadFiles){
		//根据自己的需求做
		}
		return "/ebank/draft/accept/addHonourFilePage";
	}

5.jsp 调用的方法,注意enctype

<form id="form1" name="form1" enctype="multipart/form-data" method="post"  >
<input type="hidden" name="ntransid" id ="ntransid" />
<TABLE border=0 class=top height=231 width="99%">
  <TR >
          <TD>选择文档:</TD>
          <TD>
          	<INPUT class=box name="myfiles" type="file"   onFocus="nextfield ='sshowName';"> 
          <INPUT class=button name="upload"  type=button value=" 链 接 " onclick="validate();" > 
         </TD>
 </TR>
 </TABLE>
 </FORM>
<script language="javascript">
function xxx(){//点击链接按钮
		var surl="honour_web_addAttach";
		var stype="web";
		form1.action="${systemctx}/web/withFileUpload.web?sforUrl="+surl+"&stype="+stype;
		//form1.enctype="multipart/form-data";
 		showSending();
 		form1.submit();
	
}
</script >

6.过程是在jsp,选中文件点击链接,会先进到步骤3中,包括一些参数传递等来执行完保存文件。之后回到步骤4中,根据需求修改显示和跳转。

其中遇到了一个问题就是由于在配置文件里配置了编码格式,导致文件里的内容中文不乱码了。但是文件的名称乱码了。
解决方法是:
jsp页面
<%@ page language=“java” contentType=“text/html; charset=UTF-8”%>

在步骤3上传代码的地方加上了 ~~~ response.setContentType("text/html;charset=UTF-8"); response.setHeader("content-type", "text/html;charset=UTF-8"); ~~~
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值