> Java > java지도 시간 > 본문

Java Spring MVC 업로드 및 다운로드 파일 구성 및 컨트롤러 메소드 상세 설명

高洛峰
풀어 주다: 2017-01-23 10:51:07
원래의
1835명이 탐색했습니다.

下载:

1.在spring-mvc中配置(用于100M以下的文件下载)

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<!--配置下载返回类型-->
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<!--配置编码方式-->
<property name="supportedMediaTypes" value="application/json; charset=UTF-8" />
</bean>
</list>
</property>
</bean>
로그인 후 복사

下载文件代码

@RequestMapping("/file/{name.rp}")
public ResponseEntity<byte[]> fileDownLoad(@PathVariable("name.rp")String name, HttpServletRequest request,HttpServletResponse response) {
// @PathVariable String name,
// @RequestParam("name")String name,
// System.out.println("<name>"+name);
// System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
ResponseEntity<byte[]> re = null;
try {
/**
* css,js,json,gif,png,bmp,jpg,ico,doc,docx,xls,xlsx,txt,swf,pdf
* **/
//下载防止静态加载干扰
Feelutile f=new Feelutile();
name=f.getfileformat(name);
String pathString="C:\\tempDirectory\\"+name;
File file=new File(pathString);
HttpHeaders headers=new HttpHeaders();
//String filename=URLEncoder.encode(name, "UTF-8");//为了解决中文名称乱码问题
String filename=new String(name.getBytes("utf-8"),"utf-8");
byte[] by=FileUtils.readFileToByteArray(file);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//URLEncoder.encode(filename, "UTF-8")
headers.setContentDispositionFormData("attachment",filename);
headers.setContentLength(by.length);
re=new ResponseEntity<byte[]>(by, headers, HttpStatus.CREATED);
} catch (Exception e) {
e.printStackTrace();
try {
request.getRequestDispatcher("/error/404.jsp").forward(request, response);
} catch (ServletException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return re;
}
로그인 후 복사

上传文件:

1在spring-mvc中配置

<!--4.文件上传 配置 file upload -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
<property name="maxUploadSize">
<value>1048576000</value>
</property>
<property name="maxInMemorySize">
<value>40960</value>
</property>
</bean>
로그인 후 복사

在controller中代码如下

@RequestMapping(value="/upload", method = RequestMethod.POST)
@ResponseBody
public Json upload(Doc doc, @RequestParam("uploadFile") CommonsMultipartFile file) {
Json j = new Json();
try {
String realpath = this.servletContext.getRealPath("/upload");
String uploadFileFileName = file.getOriginalFilename();
String uploadFileFileNameWithoutSpace = uploadFileFileName.replaceAll(" ", "");
String fileType = uploadFileFileNameWithoutSpace.substring(uploadFileFileNameWithoutSpace.lastIndexOf("."));
File targetFile = new File(realpath+File.separator, uploadFileFileNameWithoutSpace);
if (targetFile.exists()) {
targetFile.delete();
}
file.getFileItem().write(targetFile);
docService.upload(doc,uploadFileFileNameWithoutSpace);
j.setSuccess(true);
j.setMsg("Upload manual successfully");
}catch (Exception e) {
logger.error(ExceptionUtil.getExceptionMessage(e));
j.setMsg("Upload manual unsuccessfully");
}
return j;
}
로그인 후 복사

以上所述是小编给大家介绍的Java Spring MVC 上传下载文件配置及controller方法详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对PHP中文网的支持!

更多Java Spring MVC 上传下载文件配置及controller方法详解相关文章请关注PHP中文网!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!