许多朋友在用jspSmartUpload向Servlet传递文件的同时也想传递其他参数的值,但是因为如果用jspSmartUpload那么必须在表单form上添加属性enctype="multipart/form-data,这就导致后台无法接收到除文件以外的任何参数的值。大家自己找下核心代码,其他代码我是用来处理传过来的图片以及将数据写入数据库的,写的比较差劲,见谅。
以下为核心代码:
SmartUpload upload = new SmartUpload();//第一步,创建组件对象
upload.upload();//第二步,调用upload();
String orderId = upload.getRequest().getParameter(“orderid”);//第三步,按这个格式去取从上个页面传过来的值;
通过这三步,解决了问题!
下面是Servlet里的代码
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("GBK");
Connection con = null;
SmartUpload upload = new SmartUpload();// 创建组件对象
Statement statement = null;
try {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String url = "jdbc:mysql://127.0.0.1:3306/keshe";
con = DriverManager.getConnection(url, "root", "root");
statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
upload.initialize(this.getServletConfig(), request, response);// 初始化
upload.setMaxFileSize(1 * 1024 * 1024);// 每个文件最大1M
upload.setTotalMaxFileSize(10 * 1024 * 1024);// 总共最大10M
upload.setAllowedFilesList("jpg,png");// 允许上传jpg,png
try {
upload.upload();
String orderId = upload.getRequest().getParameter("orderid");
String mess =upload.getRequest().getParameter("message");
String petid =upload.getRequest().getParameter("petid");
String userid =upload.getRequest().getParameter("userid");
try {
int i = statement.executeUpdate("insert into pingjia values"
+ "('"+ mess + "','"+ orderId + "','"+ userid + "','"+ petid + "')");
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
Files uploadFiles = upload.getFiles();
System.out.println("上传数量: " + uploadFiles.getCount());
for(int i=0;i<uploadFiles.getCount();i++){
String fileName = uploadFiles.getFile(i).getFileName();
uploadFiles.getFile(i).saveAs("/D:\\sy/" + fileName, File.SAVEAS_PHYSICAL);// 将文件保存在磁盘根目录下的upload文件夹
}
} catch (SmartUploadException e) {
e.printStackTrace();
}
}