Springmvc之文件上传下载

 ------------------------- 前端页面 -----------------------
<script type="text/javascript" src="/x5/js/lib/jquery/jquery.form.js"></script>

<form id="kfkForm" method="post" action="" enctype="multipart/form-data">
    <table class="table-form">
<tr group="0">
               <th width="15%" ng-if="permission.fields.KfkConfig.CONFIGNAME_!=&#39;n&#39;">
                    CONFIGNAME_
                </th>
                <td width="35%" ng-if="permission.fields.KfkConfig.CONFIGNAME_!=&#39;n&#39;">
                    <input  name="CONFIGNAME_" class="form-control" type="text"  />
                </td>
                <th width="15%" ng-if="permission.fields.KfkConfig.FILEPATH_!=&#39;n&#39;">
                    FILEPATH_
                </th>
                <td width="50%" colspan="2">
                    <input type="file" id="uFile" class="form-control" name="uFile"/>
                </td>
                <td width="15%">
                    <button onclick="config('download')" style="color:red;">KFK服务器下载配置文件</button>&nbsp;&nbsp;&nbsp;<button onclick="config(&#39;upload&#39;)" style="color:red;">上传配置文件到KFK服务器</button>
                </td>
            </tr></table>
</form>
function config(type){
var url = "/x5/form/table/kfkConfigUpload";
      if(type == 'download' ){
           url = "/x5/form/table/kfkConfigDownload"
            location.href=url+"?"+$("#kfkForm").serialize();
      }else // 需要用到 ajaxSubmit提交file内容
var option = {
            type: "POST",
            url: url,
            data: {
                'type': type
            },
            success:function(data){
               
            }
        };
        $("#kfkForm").ajaxSubmit(option);
}

 ------------------------- controller -------------------------
/**
* 根据上传文件
* 修改KFK配置;
需要用注解方式获取FILE二进制内容
* @param request
* @param response
*/
@RequestMapping(value = "kfkConfigUpload" , method = RequestMethod.POST)
public void kfkConfigUpload(HttpServletRequest request, HttpServletResponse response, @RequestParam("uFile") MultipartFile uFile ) throws Exception {
ResultMessage message = null;
Object params = null;
try {
Map<String, String> map =new HashMap<>();
Enumeration<String> er = request.getParameterNames();
while (er.hasMoreElements()) {
String name = (String) er.nextElement();
String value = request.getParameter(name);
map.put(name, value);
}

CommonDao commonDao = AppUtil.getBean(CommonDao.class);

String type = map.get("type");

ConfigFileInfo fileInfo = new ConfigFileInfo();
HttpPostUtils ups = new HttpPostUtils();
fileInfo.setClientUrl(map.get("URL_"));
fileInfo.setConfigName(map.get("CONFIGNAME_"));

String p = request.getSession().getServletContext().getRealPath("");
String fPath = p.substring(0, p.indexOf("x5")+2) + "\\" + uFile.getOriginalFilename();
fileInfo.setTempFilePath(fPath);
File path = new File(fPath);
FileOutputStream outputStream = new FileOutputStream(path);
outputStream.write(uFile.getBytes());
outputStream.close();

ups.postFile( fileInfo );

} catch (Exception e) {
e.printStackTrace();
message = new ResultMessage(ResultMessage.FAIL, e.getCause().getMessage() );
} finally {
writeResultMessage(response.getWriter(), message);
}
}

/**
* 下载KFK配置;
* @param request
* @param response
*/
@RequestMapping(value = "kfkConfigDownload")
public void kfkConfigDownload(HttpServletRequest request, HttpServletResponse response ) throws Exception {
ResultMessage message = null;
BufferedInputStream dis = null;
BufferedOutputStream fos = null;
Object params = null;
try {
Map<String, String> map =new HashMap<>();
Enumeration<String> er = request.getParameterNames();
while (er.hasMoreElements()) {
String name = (String) er.nextElement();
String value = request.getParameter(name);
map.put(name, value);
}

CommonDao commonDao = AppUtil.getBean(CommonDao.class);

ConfigFileInfo fileInfo = new ConfigFileInfo();
HttpPostUtils ups = new HttpPostUtils();
fileInfo.setClientUrl(map.get("URL_"));
fileInfo.setConfigName(map.get("CONFIGNAME_"));

String p = request.getSession().getServletContext().getRealPath("");
String fPath = p.substring(0, p.indexOf("x5")+2) + "\\" ;
fileInfo.setTempFilePath(fPath);
String fileName = ups.downloadFile( fileInfo );
message = new ResultMessage(ResultMessage.SUCCESS, fPath+fileName );

File file = new File(fPath+fileName);
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));

dis = new BufferedInputStream( new FileInputStream(file) );
fos = new BufferedOutputStream(response.getOutputStream());

byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = dis.read(buff, 0, buff.length))) {
fos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
message = new ResultMessage(ResultMessage.FAIL, e.getCause().getMessage() );
} finally {
if (dis != null)
try{
dis.close();
}catch (Exception e){
e.printStackTrace();
}
if (fos != null)
try{
fos.close();
}catch (Exception e){
e.printStackTrace();
}
writeResultMessage(response.getWriter(), message);
}
}

 ------------------------- 工具类 -------------------------
public static void postFile(ConfigFileInfo fileInfo) {
PostMethod filePost = new PostMethod(fileInfo.getClientUrl() + "/uploadConfigFile");
File tmpfile = new File(fileInfo.getTempFilePath());
if (!tmpfile.exists()) {
logger.error("temp file is not found!");
return;
}
if ( StringUtil.isEmpty(fileInfo.getClientUrl())) {
logger.error("client url is empty!");
return;
}
if ( StringUtil.isEmpty(fileInfo.getConfigName())) {
logger.error("config name is not setup!");
return;
}

try {
Part[] parts = { new FilePart("file", tmpfile),
new StringPart("configName", fileInfo.getConfigName()) };
filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
int status = client.executeMethod(filePost);
if (status == HttpStatus.SC_OK) {
String responseMsg = new String(filePost.getResponseBody(),"utf-8");
System.out.println(responseMsg);
// 上传成功
} else {
System.out.println("上传失败");
// 上传失败
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
filePost.releaseConnection();
}

}


public static String downloadFile(ConfigFileInfo fileInfo) {
String fileName = "";

HttpClient client = new HttpClient();
PostMethod method = new PostMethod(fileInfo.getClientUrl() + "/getConfigFile");
client.getHttpConnectionManager().getParams().setConnectionTimeout(1000 * 60 * 5);
client.getHttpConnectionManager().getParams().setSoTimeout(1000 * 60 * 10);
try {
method.setParameter("configName", fileInfo.getConfigName());
//method.setDoAuthentication(true);
int status = client.executeMethod(method);
if (status != 200) {
throw new RuntimeException("the status is " + status);
}

InputStream input = method.getResponseBodyAsStream();
Header[] hs = method.getResponseHeaders();

for (Header h : hs) {
System.out.println(h.getName() + ":" + h.getValue());
if(h.getValue().indexOf("filename=")>-1){
fileName = h.getValue().substring(h.getValue().indexOf("=")+1);
}
}
OutputStream out = new FileOutputStream(new File(fileInfo.getTempFilePath()+fileName));
int length = 0;
byte [] rbody = new byte[1024];
int readNum = 0;
while ((readNum = input.read(rbody)) > 0) {
out.write(rbody,0,readNum);
length += readNum;
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
method.releaseConnection();
}
return fileName;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
当使用Spring MVC进行文件上传时,需要注意以下几点: 1. 首先,在Spring MVC配置文件中启用multipart解析器。可以通过在servlet-context.xml或applicationContext.xml文件中添加以下配置来完成: ```xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"> <context:component-scan base-package="com.example" /> <mvc:annotation-driven /> <!-- 配置multipart解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10000000"/> </bean> </beans> ``` 这里我们使用了CommonsMultipartResolver类来处理文件上传,还可以通过maxUploadSize属性设置上传文件的最大大小。 2. 在Controller中编写处理文件上传的方法,并使用@RequestParam注释来接收上传的文件。例如: ```java @RequestMapping(value="/upload", method=RequestMethod.POST) public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) { if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); // 文件上传逻辑处理 } catch (Exception e) { e.printStackTrace(); } } return "redirect:/successUrl"; } ``` 在上面的代码中,我们使用@RequestParam注释将上传的文件绑定到MultipartFile对象中,并使用getBytes()方法获取文件内容。 3. 最后,在表单中添加文件上传控件,并指定form的enctype属性为“multipart/form-data”。例如: ```html <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" value="上传" /> </form> ``` 这样就完成了文件上传的全部过程。注意,在实际应用中,还需要对上传的文件进行安全检查,例如检查文件类型、文件大小等,以确保应用的安全性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kingwin28

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值