FormFile file=manform.getFile()
String newfileName = null
String newpathname=null
String fileAddre="/numUp"
try {
InputStream stream = file.getInputStream()// 把文件读入
String filePath = request.getRealPath(fileAddre)//取系统当前路径
File file1 = new File(filePath)//添加了自动创建目录的功能
((File) file1).mkdir()
newfileName = System.currentTimeMillis()
+ file.getFileName().substring(
file.getFileName().lastIndexOf('.'))
ByteArrayOutputStream baos = new ByteArrayOutputStream()
OutputStream bos = new FileOutputStream(filePath + "/"
+ newfileName)
newpathname=filePath+"/"+newfileName
System.out.println(newpathname)
// 建立一个上传文件的输出流
System.out.println(filePath+"/"+file.getFileName())
int bytesRead = 0
byte[] buffer = new byte[8192]
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead)// 将文件写入服务器
}
bos.close()
stream.close()
} catch (FileNotFoundException e) {
e.printStackTrace()
} catch (IOException e) {
e.printStackTrace()
}
1.下载简单,无非是把服务器上的文件或者数据库中的BLob(或其他二进制型),用流读出来,然后写到客户端即可,要注意 ContentType。2.上传,可以用Apache Commons Upload等开源工具,或者自己写:
form要用enctype="multipart/form-data"
然后服务器端也是用IO把客户端提交的文件流读入,然后写到服务器的文件系统或者数据库里。不同的数据库对Lob字段操作可能有所不同,建议用Hibernate,JPA等成熟的ORM框架,可以不考虑数据库细节。
import java.io.IOExceptionimport java.io.PrintWriter
import javax.servlet.ServletException
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import com.jspsmart.upload.*
import net.sf.json.JSONObject
import action.StudentAction
public class UploadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response)
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean result=true
SmartUpload mySmartUpload=new SmartUpload()
mySmartUpload.initialize(this.getServletConfig(), request,response)
mySmartUpload.setTotalMaxFileSize(50*1024*1024)//大小限制
mySmartUpload.setAllowedFilesList("doc,docx")//后缀名限制
try {
mySmartUpload.upload()
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0)
myFile.saveAs("/file/"+1+".doc")//保存目录
} catch (SmartUploadException e) {
e.printStackTrace()result=false
}
//*****************************//
response.setContentType("text/htmlcharset=UTF-8")
response.setHeader("Cache-Control","no-cache")
PrintWriter out = response.getWriter()
out.print(result)
out.flush()
out.close()
}
}
//我这是ajax方式的,不想这样,把//**********************//以下部分修改就行了
//需要SmartUpload组件,去网上下个就行了,也有介绍的