Java实现服务器文件上传和保存操作 (java 保存上传 文件到服务器)
随着互联网的发展和普及,文件上传和保存操作在服务器端扮演着越来越重要的角色。Java作为一种广泛使用的编程语言,拥有强大的API和丰富的库,能够轻松地实现文件上传和保存操作。本文将介绍如何使用。
一、选择合适的框架
在实现文件上传和保存操作时,我们可以选择一些开源框架,例如Apache的Commons FileUpload和Servlet 3.0规范中新增的Part接口。这些框架已经封装了文件上传的各种操作,我们可以更加方便地使用它们。
二、实现文件上传操作
使用Apache Commons FileUpload实现文件上传操作,需要以下步骤:
1. 在pom.xml中添加以下依赖:
“`
commons-fileupload
commons-fileupload
1.4
“`
2. 创建一个Servlet用于处理上传的文件。在其中解析请求并获取上传的文件:
“`
@WebServlet(“/upload”)
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = “”;
InputStream inputStream = null;
Part filePart = request.getPart(“file”);
fileName = filePart.getSubmittedFileName();
inputStream = filePart.getInputStream();
//在这里处理上传的文件
//……
}
}
“`
3. 在web.xml中配置Servlet:
“`
FileUploadServlet
xxx.FileUploadServlet
FileUploadServlet
/upload
“`
三、实现文件保存操作
在获取到上传的文件之后,我们需要将其保存到服务器上。下面介绍两种保存文件的方法。
1. 使用FileOutputStream保存文件
“`
FileOutputStream outputStream = new FileOutputStream(new File(“文件保存路径”));
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputStream.close();
“`
这种方法比较简单,只需要创建一个FileOutputStream对象和一个缓冲区,然后将文件流写入到文件中即可。
2. 使用Java 7的Files类保存文件
“`
Files.write(Paths.get(“文件保存路径”), inputStream.readAllBytes());
inputStream.close();
“`
这种方法使用了Java 7中的Files类,可以更加简洁地实现文件保存操作。
四、实现上传进度条
为了让用户更加直观地了解文件上传的进度,我们可以实现上传进度条。可以在Servlet中添加以下代码:
“`
long fileSize = filePart.getSize();
byte[] buffer = new byte[8192];
int read;
long uploaded = 0;
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
uploaded += read;
int percent = (int) (uploaded * 100 / fileSize);
//更新上传进度
}
“`
五、
以上就是的详细步骤。使用Java编写文件上传和保存操作,不仅可以提高系统的可靠性和安全性,而且能够提供更加友好和直观的用户体验。希望本文能够对大家有所帮助。
相关问题拓展阅读:
- java实现图片上传至服务器并显示,如何做?
java实现图片上传至服务器并显示,如何做?
使用一些已有的组件帮助我们实现这种上传功能。
常用的上传组件:
Apache 的 Commons FileUpload
JavaZoom的UploadBean
漏差 jspSmartUpload
以下,以FileUpload为例讲解
1、在jsp端
要注意enctype=”multipart/form-data”锋搜逗
然后只需要放置一个file控件,并执行submit操作即可
2、web端
核心代码如下:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding(“UTF-8”);
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
System.out.println(“表单参数名:” + item.getFieldName() + “,表单参银卖数值:” + item.getString(“UTF-8”));
} else {
if (item.getName() != null && !item.getName().equals(“”)) {
System.out.println(“上传文件的大小:” + item.getSize());
System.out.println(“上传文件的类型:” + item.getContentType());
System.out.println(“上传文件的名称:” + item.getName());
File tempFile = new File(item.getName());
File file = new File(sc.getRealPath(“/”) + savePath, tempFile.getName());
item.write(file);
request.setAttribute(“upload.message”, “上传文件成功!”);
}else{
request.setAttribute(“upload.message”, “没有选择上传文件!”);
}
}
}
}catch(FileUploadException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
request.setAttribute(“upload.message”, “上传文件失败!”);
}
request.getRequestDispatcher(“/uploadResult.jsp”).forward(request, response);
}
给你段代码,是用来在ie上显示图片的(servlet):
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter(“id”);
File file = new File(getServletContext().getRealPath(“/”)+”out”+”/”+id+”.gif”);
response.setCharacterEncoding(“gb2312”);
response.setContentType(“doc”);
response.setHeader(“Content-Disposition”, “attachment; filename=” + new String(file.getName().getBytes(“gb2312″),”iso8859-1”));
System.out.println(new String(file.getName().getBytes(“gb2312″),”gb2312”));
OutputStream output = null;
FileInputStream fis = null;
try
{
output = response.getOutputStream();
fis = new FileInputStream(file);
byte b = new byte;
int i = 0;
while((i = fis.read(b))!=-1)
{
output.write(b, 0, i);
}
output.write(b, 0, b.length);
output.flush();
response.flushBuffer();
}
catch(Exception e)
{
System.out.println(“Error!”);
e.printStackTrace();
}
finally
{
if(fis != null)
{
fis.close();
fis = null;
}
if(output != null)
{
output.close();
output = null;
}
}
}
这个程序的功能是根据传入的文基腔件名(id),来为浏览器返回图片流,显示在<img src="
” align=”center”>标签里
标签的格式写成如下槐锋碧:
—-pic—
显示的是111.gif这个图片
你上面的问题:
1.我觉得你的第二个办法是对的,我们也是这样做的,需要的是把数据库的记录id号传进servlet,然后读取这条记录中的路径信息,生成流以后返回就是了
关于上传文件的问题,我记得java中应该专门铅举有个负责文件上传的类,你调用就行了,上传后存储在指定的目录里,以实体文件的形式存放
你可以参考这个:
回复:
1.是的,在response中写入流就行了
2.是发到servlet中的,我们一般都是写成servlet,短小精悍,使用起来方便,struts应该也可以,只是我没有试过,恩,你理解的很对
网上可以下到上传控件。。都是写好的 我晌亮宴这也有 太长了就不发上来了 你要是要我可以给你 你只要在键或servlet里调用里面的方宴银法就行了
用common-fileupload几行代码搞定
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){
RecordForm rform=(RecordForm)form;
FormFile formFile=rform.getImage();
String path=request.getSession().getServletContext().getRealPath(“/”);
RecordService service=(RecordService) BeanFactory.getBean(BeanFactory.RECORDSERVICE);
StudentService stuservice=(StudentService) BeanFactory.getBean(BeanFactory.STUDENTSERVICE);
Student student=(Student) request.getSession().getAttribute(“student”);
Record record=(Record) request.getSession().getAttribute(“record”);
student.setName(rform.getName());
student.setGender(rform.getGender());
record.setAddress(rform.getAddress());
record.setAdmitdate(Date.valueOf(rform.getAdmitdate()));
record.setBirthday(Date.valueOf(rform.getBirthday()));
record.setFromaddr(rform.getFromaddr());
record.setRemarks(rform.getRemarks());
record.setFeature(rform.getFeature());
record.setStudent(student);
student.setRecord(record);
if(formFile.getFileSize()!=0){
String image=getPath(formFile,path,student.getId());
record.setImage(image);
}
try {
stuservice.updateStudent(student);
service.updateRecord(record);
request.setAttribute(“record”, record);
request.setAttribute(“student”, student);
return mapping.findForward(“success”);
} catch (ServiceException e) {
request.setAttribute(“error”, e.getMessage());
e.printStackTrace();
return mapping.findForward(“failure”);
}
}
private String getPath(FormFile formFile, String path, String studentid) {
InputStream is = null;
FileOutputStream fos = null;
File file = new File(path + “/” + studentid + “/”);
if (!file.exists())
file.mkdir();
try {
is = formFile.getInputStream();
fos = new FileOutputStream(path + “/” + studentid + “/”
+ formFile.getFileName());
byte buffer = new byte;
int count = 0;
while ((count = is.read(buffer, 0, buffer.length)) != -1)
fos.write(buffer, 0, count);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (is != null)
is.close();
if (fos != null)
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return “/”+ studentid+”/”+formFile.getFileName();
}
}
关于java 保存上传 文件到服务器的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。
编辑:广州鸿名健康科技有限公司
标签:上传,文件,文件上传,操作,上传文件