上传下载

上传:

jsp:

<form:form commandName="uploadForm" method="post" action="${ctx}/purcorder/upload.do" enctype="multipart/form-data" >
<div class="div0"> 
<input type="hidden" value="${p.pkPoid }" name="pkPoid">
</div>

<div> <span class="font4">Locate the file then click upload.</span><input type="file" name="uploadFile"/></div>

<div class="savebutton"><input type="submit" value="Save and Proceed"/></div>
</div>
</div>


</form:form>


controler:
@RequestMapping(value = "/upload.do", method = RequestMethod.POST)
public String upload(@RequestParam("uploadFile") MultipartFile multipartFile, @ModelAttribute("uploadForm") Object uploadForm, BindingResult errors,HttpServletRequest request, ModelMap model) {
logger.debug("uploading file...{}", request);
String pkPoid = request.getParameter("pkPoid");
final String filePath = "/fileupload.properties";
try {
FileHandlerFactory handler = FileHandlerFactory.getInstance(filePath, request);
//transfer file to disk.
final String storePath = handler.getFileConfig().getProperty("com.pccw.oframework.utility.upload.persistenceFolder");
String dbFileName = multipartFile.getOriginalFilename()+(new Date()).getTime();
File dest = new File(storePath+"/"+ dbFileName);
logger.info("transfering file to {}", dest.getAbsolutePath());
multipartFile.transferTo(dest);


//invoke handler to process file.
ValidationResult result = handler.handleFile(dest);


Set<Map.Entry<String,String>> ferrs= result.getErrors().entrySet();
for(Entry<String,String> entry: ferrs){
errors.reject(entry.getKey(), entry.getValue());
}
//add file handler error to request.
model.addAttribute("fileErrorsMap", handler.getFileErrorsMap());


//获得上传的所有文件
List<PDTO> pLDTO = pService.getFileInforByPoId(pkPoid);
model.addAttribute("pLDTO", pLDTO);
} catch (Exception e1) {
logger.error("Error in intiating File Handler.", e1);
errors.reject("", "Error in intiating File Handler.");
}
return "redirect:/purc/view/"+pkPoid+".do";

}

--------------------------------------------------------------------------------------------------------------------------------------

下载:

jsp:
<c:forEach var="o" items="${pLDTO}">
<div class="trow">
<div class="c c1"><a href="${ctx}/purcorder/download/${o.pouploads.pkPouploadId}.do">${o.pouploads.fileName}</a></div>
<button>Edit</button>
</div>
<div class="c cclear"></div>
</div>
</c:forEach>


control:
@RequestMapping("/download/{pkPouploadId}.do")
public String download(ModelMap model, HttpServletRequest request,
HttpServletResponse response,@PathVariable("pkPouploadId") String pkPouploadId) {


Pouploads Pouploads = pouploaderService.getPouploadsById(pkPouploadId);
// 输出的应用类型
response.setCharacterEncoding("UTF-8");
// filenames是自定义的文件名
String fileName = Pouploads.getFileName();


final String filePath = "/fileupload.properties";




FileHandlerFactory handler = null;
try {
handler = FileHandlerFactory.getInstance(filePath, request);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
final String storePath = handler.getFileConfig().getProperty("com.pccw.oframework.utility.upload.persistenceFolder");

File file = new File(storePath+"/"+ dbFileName);
/*try {
fileName = new String(file.getName().getBytes("GBK"),"iso8859-1");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}*/
response.setHeader("Content-Disposition", "attachment;filename="
+ fileName);
response.setContentType("application/octet-stream");

InputStream is = null;
OutputStream out = null;
try {
is = new FileInputStream(file);
out = response.getOutputStream();
for (int c = is.read(); c != -1; c = is.read()) {
out.write(c);
}

is.close();
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}finally{
close(is,out);
}
return null;
}
/**
* @Description:关闭IO流
*/
private void close(InputStream is, OutputStream out) {
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
-----------------------------------------------------------------------------------------------------------------------------------

下载2


HTML:
<td><input type="button" value="下载模版" class="export" οnclick="downloadTemplate();"/></td>


js:
//下载excel模板
    function downloadTemplate(){
        //下载模版的action地址
           var url = "<%=request.getContextPath()%>/importAndExport.do?method=down";
        var form=document.getElementById("archExampleForm");
         form.setAttribute("action",url);
         form.submit();
    }


action:
/**
     * @Description:下载模版
     */
    public void down(ActionMapping mapping, ActionForm baseForm, HttpServletRequest request, HttpServletResponse response) throws    Exception{
        String excelTemplatPath = request.getParameter("excelTemplatPath");
        // 服务器端源文件路径
        String  realPath = request.getRealPath("")+"//WEB-INF//template//xls//"+excelTemplatPath;
        String excelTemplatFileName = request.getParameter("excelTemplatFileName");
        System.out.println("excelTemplatFileName-----------------------------"+excelTemplatFileName);
        // 文件名
        String fileName =excelTemplatFileName+"(数据导入模板).xls";
        ImportExternalDataToDB.downloadFile(response, fileName, realPath);
    }


下载类:
public static void downloadFile( HttpServletResponse response,String fileName,String realPath){
        try{
            response.setContentType("application/x-msdownload");
            // 设置下载框文件名显示内容及编码
            response.addHeader("Content-Disposition","attachment; filename=\"" + java.net.URLEncoder.encode(fileName,"UTF-8") + "\"");
            ServletOutputStream out = response.getOutputStream();
            InputStream input = new FileInputStream(new File(realPath));
            byte[] b = new byte[4096];
            int len;
            while ((len = input.read(b)) > 0) {
                out.write(b, 0, len);
            }
            input.close();
            out.flush();
            out.close();
        }catch (Exception e) {
            e.printStackTrace();
        }    
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring MVC是一个基于Java的开源框架,用于构建Web应用程序。它提供了一种模型-视图-控制器(MVC)的架构模式,用于将应用程序的不同部分分离开来,以实现更好的可维护性和可扩展性。 下面是一个简单的Spring MVC上下载的实例: 1. 配置文件: 首先,在Spring MVC的配置文件中添加以下配置: ```xml <!-- 配置文件上 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10485760"/> <!-- 设置最大上文件大小为10MB --> </bean> ``` 2. 控制器类: 创建一个控制器类,用于处理上下载请求。以下是一个示例: ```java @Controller public class FileController { @RequestMapping(value = "/upload", method = RequestMethod.POST) public String uploadFile(@RequestParam("file") MultipartFile file) { // 处理文件上逻辑 if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); // 保存文件到服务器或者其他操作 return "redirect:/success"; // 上成功后跳转到成功页面 } catch (IOException e) { e.printStackTrace(); } } return "redirect:/error"; // 上失败后跳转到错误页面 } @RequestMapping(value = "/download", method = RequestMethod.GET) public ResponseEntity<Resource> downloadFile() { // 处理文件下载逻辑 // 构建文件资源对象 Resource fileResource = new FileSystemResource("path/to/file"); // 设置响应头 HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=file.txt"); // 返回文件资源和响应头 return ResponseEntity.ok() .headers(headers) .contentLength(fileResource.contentLength()) .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(fileResource); } } ``` 3. 前端页面: 在前端页面中添加上下载的表单和按钮。以下是一个简单的示例: ```html <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" value="上" /> </form> <a href="/download">下载文件</a> ``` 这是一个简单的Spring MVC上下载的实例。你可以根据实际需求进行修改和扩展。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值