1甲馋、普通方式
前端代碼
<form action="UploadServlet" method="post" enctype="Multipart/form-data">
name:<input type="text" name="sname"><br/>
age:<input type="text" name="sage"><br/>
photo:<input type="file" name="sphoto"><br/>
<input type="submit" value="Submit">
</form>
<a href="DownloadServlet?filename=圖片.jpg">Download</a><br/>
后臺(tái)UploadServlet代碼
@WebServlet("/downloadServlet")
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//得到上傳文件的保存目錄迄损,將上傳的文件放在webRoot目錄下(但是一般為了安全放在WEB-INF目錄下,不允許外界直接訪問(wèn)痊远,保證上傳的安全)
String path = this.getServletContext().getRealPath("/upload");
File file = new File(path);
//判斷上傳文件的保存目錄是否存在
if(!file.exists() && !file.isDirectory()){
System.out.println(path + "目錄不存在,需要?jiǎng)?chuàng)建拗引!");
file.mkdir(); //創(chuàng)建目錄
}
request.setCharacterEncoding("utf-8");
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart){
DiskFileItemFactory factory = new DiskFileItemFactory(1024*10,new File("D:\\temp"));
ServletFileUpload upload = new ServletFileUpload(factory);
//upload.setSizeMax(1024*200);
try {
List<FileItem> items = upload.parseRequest(request);
for(FileItem item:items){
if(item.isFormField()){
System.out.println(item.getFieldName());
}else{
String filename = item.getName();
File file = new File("D:\\upload", filename);
item.write(file);
System.out.println("上傳成功");
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
后臺(tái)DownloadSrvlet代碼
@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String filename = new String(request.getParameter("filename").getBytes("iso-8859-1"),"utf-8");
response.addHeader("Content-Type", "application/octet-stream");//二進(jìn)制流矾削,可以下載任何類型,具體可查HTTP Content-Type對(duì)照表
String agent=request.getHeader("User-agent").toLowerCase();
if(agent.contains("firefox")){
response.addHeader("Content-Disposition", "attachment;filename==?UTF-8?B?"+new String(Base64.encodeBase64(filename.getBytes("utf-8")))+"?=");
}
if(agent.contains("edge")||agent.contains("chrome")){
response.addHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(filename,"utf-8"));
}else{
response.addHeader("Content-Disposition", "attachment;filename="+filename);
}
InputStream is = getServletContext().getResourceAsStream("/res/"+filename);
ServletOutputStream os = response.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(is);
BufferedOutputStream bos = new BufferedOutputStream(os);
int data = -1;
while((data=bis.read())!=-1){
bos.write(data);
}
bos.flush();
if(bis!=null)
bis.close();
if(bos!=null)
bos.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
2欲间、SpringMVC實(shí)現(xiàn)文件上傳
a.導(dǎo)入commons-fileupload.jar和commons-io.jar
b.在SpringMVC配置文件中配置CommonsMultipartResolver
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 上傳單個(gè)文件的最大值断部,單位Byte;如果-1猎贴,表示無(wú)限制 -->
<property name="maxUploadSize" value="102400"></property>
</bean>
c.在controller中編寫(xiě)處理方法
@RequestMapping(value="testUpload") //abc.png //注意文件的表單是一個(gè)MultipartFile類型的
public String testUpload(@RequestParam("desc") String desc , @RequestParam("file") MultipartFile file ) throws IOException {
System.out.println("文件描述信息:"+desc);
//jsp中上傳的文件:file
InputStream is = file.getInputStream();//IO
String fileName = file.getOriginalFilename();
OutputStream out = new FileOutputStream("d:\\"+fileName) ;
byte[] buf = new byte[1024];
int len = -1;
while(( len = is.read(buf)) !=-1 ) {
out.write(bs, 0, len);
}
out.close();
is.close();
//將file上傳到服務(wù)器中的 某一個(gè)硬盤(pán)文件中
System.out.println("上傳成功她渴!");
return "success";
}
3、HTML實(shí)現(xiàn)文件下載
window.open("url"); //圖片趁耗、xml等文件會(huì)直接在窗口打開(kāi)
//注意使用Idea時(shí)疆虚,放入的靜態(tài)資源可能不能及時(shí)更新到服務(wù)器(out中)
$("#myButton").click(function () {
// window.open("res/desk.png");
// window.open("res/web.xml");
// window.open("res/111.xls");
//window.location.href = "excelServlet";
window.location.href = "res/desk.png";
});
<a href="文件路徑" download="文件名">下載</a>
<a href="/JavaWeb_war_exploded/res/desk.png" download="desk.png">通過(guò)a標(biāo)簽下載文件1</a>
<a href="res/desk.png" download="desk.png">通過(guò)a標(biāo)簽下載文件2</a>