前台
<script type="text/javascript">
function zhq(){
document.getElementById("music_name").innerHTML="冰雨";
document.getElementById("music_content").innerHTML="<embed src='myFolders/aa.mp3' hidden=true>";
}
</script>
<body>
<form action="UploadServlet?zhang=upload" method="post" enctype="multipart/form-data">
输入文件名<input type="text" name="fileName"/>
<input type="file" name="filePath" />
<input type="submit" value="提交"/>
</form>
<a href="UploadServlet?zhang=download&file=test.doc">下载</a>
<a href="javascript:void(0)" onclick="zhq()">音乐</a>
<div id="music">
<ul id="music_name"></ul>
<ul id="music_content"></ul>
</div>
</body>
</html>
后台
package myUpload;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
public class UploadServlet extends HttpServlet {
public void destroy() {
super.destroy();
}
/**
* 重写父类的init方法将config初始化
*/
public void init(ServletConfig config) throws ServletException {
this.config=config;
}
//声明一个config对象
private ServletConfig config;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String zhang=request.getParameter("zhang");
//第一步创建SmartUpload对象
SmartUpload su=new SmartUpload();
//第二步实例化SmartUpload对象
su.initialize(config, request, response);
if(zhang.equals("upload")){
try {
//第三部上传
su.upload();
} catch (SmartUploadException e) {
System.out.println("文件有误");
e.printStackTrace();
}
String fileName=su.getRequest().getParameter("fileName");
String fileExt=su.getFiles().getFile(0).getFileExt();
Date date=new Date();
SimpleDateFormat zhq=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String filexx=""+zhq.format(date);
//打印文件名
System.out.println(filexx+"."+fileExt);
su.setAllowedFilesList("jpg");
try {
//打印文件大小
System.out.println(su.getFiles().getFile(0).getSize());
//第四步保存
su.getFiles().getFile(0).saveAs("/myFolders/"+filexx+"."+fileExt);
} catch (SmartUploadException e) {
System.out.println("存不了");
e.printStackTrace();
}
request.setAttribute("aa", "aaaaa");
RequestDispatcher dispatcher=request.getRequestDispatcher("result.jsp");
dispatcher.forward(request, response);
}
if(zhang.equals("download")){
String file=request.getParameter("file");
try {
su.downloadFile("/myFolders/"+file);
} catch (SmartUploadException e) {
e.printStackTrace();
}
}
}
}