您好,欢迎来到爱go旅游网。
搜索
您的当前位置:首页大文件上传方案

大文件上传方案

来源:爱go旅游网
具体使用步骤:

1.在Spring配置文件添加 class=\"org.springframework.web.multipart.commons.CommonsMultipartResolver\">

//这里可以文件大小,这里配的是100M

2.编写上传处理Controller 例如:

package com.sinolife.test.upload;

import java.io.FileOutputStream; import java.io.InputStream;

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;

@Controller

public class Test {

@RequestMapping(\"/Upload\")

public String processUpload(@RequestParam() MultipartFile file) throws Exception { /**

* 1.这里需要注意各个流被正确关闭,以及在io异常情况下的关闭处理

* 2.读取MultipartFile必须用流接口读,写到硬盘上然后关闭,然后再吧这个文件交给其他程序处理, * 如果直接调用MultipartFile。getbytes大文件会导致服务器OOM而崩溃。禁止使用这个getbytes接口。

* 另外服务器上用完的文件记得删除,防止垃圾数据占用过多磁盘 */

if (!file.isEmpty()) {

FileOutputStream fos = new FileOutputStream(\"d:/\" + file.getOriginalFilename()); InputStream in=file.getInputStream(); byte[] buf=new byte[2048]; int length=in.read(buf); while(length!=-1) {

fos.write(buf, 0, length); length=in.read(buf); }

fos.flush(); fos.close(); in.close();

//这里可以调用处理这个文件的服务 }

System.out.println(\"name: \" + file.getOriginalFilename() + \" size: \"

+ file.getSize()); return \"redirect:/welcome\"; } }

3.编写上传页面

下载: /**

* 把附件内容写入流中 * @param response * @param entity

* @throws IOException */

protected void forwardDownload(HttpServletResponse response,EmailTemplate entity)throws IOException{

byte[] fileContent = entity.getTemplateFile();//模板内容 String fileName = entity.getFileName();//模板名称 response.setCharacterEncoding(\"UTF-8\");

response.setContentType(\"application/octet-stream\");

response.setHeader(\"Content-Disposition\ + new String(fileName.getBytes(), \"ISO8859_1\")); response.getOutputStream().write(fileContent); response.getOutputStream().close(); response.flushBuffer(); }

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- igat.cn 版权所有 赣ICP备2024042791号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务