1

我做了一个上传功能,它运行良好。它将上传的文件存储到“C:/apache-tomcat-6.0.36/webapps/Upload/” 但是,现在我想让这个应用程序能够下载文件。

我一直在谷歌搜索,但我找不到。

这是模型的代码:

public class UploadForm {

private String name = null;
private CommonsMultipartFile file = null;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public CommonsMultipartFile getFile() {
    return file;
}
public void setFile(CommonsMultipartFile file) {
    this.file = file;
    this.name = file.getOriginalFilename();
}

}

这是控制器:

@Controller

@RequestMapping(value="/FileUploadForm.htm") 公共类 UploadFormController 实现 HandlerExceptionResolver{

private String filePath = "C:/apache-tomcat-6.0.36/webapps/Upload/";

@RequestMapping(method=RequestMethod.GET)
public String showForm(ModelMap model){
    UploadForm form = new UploadForm();
    model.addAttribute("FORM", form);
    return "FileUploadForm";
}

@RequestMapping(method=RequestMethod.POST)
public String processForm(@ModelAttribute(value="FORM") UploadForm form,
        HttpServletRequest request,@RequestParam CommonsMultipartFile[] file) throws Exception {

        System.out.println(filePath);

        if(file != null && file.length > 0) {
            for(CommonsMultipartFile aFiles : file) {
                if(!aFiles.getOriginalFilename().equals("")) {
                    aFiles.transferTo(new File(filePath + aFiles.getOriginalFilename()));
                }
            }
            return "success";
        }else{
            return "FileUploadForm";
        }   
}


@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public ModelAndView resolveException(HttpServletRequest arg0,
        HttpServletResponse arg1, Object arg2, Exception exception) {
    Map<Object, Object> model = new HashMap<Object, Object>();
    if (exception instanceof MaxUploadSizeExceededException)
    {
        model.put("errors", "File size should be less then "+((MaxUploadSizeExceededException)exception).getMaxUploadSize()+" byte.");
    } else
    {
        model.put("errors", "Unexpected error: " + exception.getMessage());
    }
    model.put("FORM", new UploadForm());
    return new ModelAndView("/FileUploadForm", (Map) model);

}

}

这是 FileUploadForm.jsp 页面:

        <form:form commandName="FORM" enctype="multipart/form-data" method="POST">
    <table>
        <tr><td colspan="2" style="color: red;"><form:errors path="*" cssStyle="color : red;"/>
            ${errors}
        </td></tr>
        <tr>
            <td>Choose File:</td>
            <td><form:input type="file" name="file" path="file" /></td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value="Upload File" /></td>
        </tr>
    </table>
    </form:form>

最后,这是 Success.jsp 页面:

    <h3 style="color: green;">File has been uploaded successfully.</h3> <br>
File Name : ${FORM.name}.
</br><a href="...">Download this file here</a>

非常感谢和欢迎任何想法或解决方案。

最好的问候,尤努斯

4

0 回答 0