使用smartupload.jar实现文件上传
1.将jar包添加到项目中:smartupload.jar
2.准备上传的页面
<%--
Created by IntelliJ IDEA.
User: Administrator
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
名称:<input type="text" name="uname" ><br>
文件:<input type="file" name="myfile"><br>
<input type="submit" value="上传">
</form>
</body>
</html>
注:
(1)form标签中要添加enctype属性
(2)提交方式必须是post
(3).开始获取数据,保存文件
package com.yhp.web;
import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
/**
* Administrator
* uploadProject
* 面向对象面向君 不负代码不负卿
*/
@WebServlet(value = "/upload")
public class UploadServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.创建对象
SmartUpload smartUpload = new SmartUpload();
//2.初始化
PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, req, resp, null, false, 1024 * 5, true);
smartUpload.initialize(pageContext);
//3.设置编码方式
smartUpload.setCharset("utf-8");
//4.上传
try {
smartUpload.upload();
} catch (SmartUploadException e) {
e.printStackTrace();
}
//5.保存文件
File file = smartUpload.getFiles().getFile(0);
//6.得到文件的基本信息
String fileName = file.getFileName();
//指定服务器保存文件的路径
String url="uploadfile/"+fileName;
//保存文件
try {
file.saveAs(url,File.SAVEAS_VIRTUAL);
} catch (SmartUploadException e) {
e.printStackTrace();
}
//是否保存成功?--->如果上传成功,则页面中显示该文件
req.setAttribute("filename",fileName);
//7.测试:除文件以外的内容如何获取
String uname = smartUpload.getRequest().getParameter("uname");
System.out.println("uname="+uname);
//8.跳转页面
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
}
注:
(1)此时如果表单中有其他数据时,不能通过request直接获取,需要通过SmartUpload对象获取
String name=su.getRequest().getParameter(“uname”);
并且该代码要在SmartUpload操作完成后添加
(2)解决乱码:
new String(name.getBytes(“GBK”),”utf-8”)
注:斜杠方向:/
注意: