前端使用form表单提交图片后,java后台怎么获取该图片? 120
前端页面使用的是<formaction="<c:urlvalue="/shop/getorderphoto.do"/>"method="POST"><tablealign...
前端页面使用的是
<form action="<c:url value="/shop/getorderphoto.do"/>" method="POST">
<table align="center" border="0">
<tr>
<td colspan="2">请输入订单详细图片
<br /> </td>
</tr>
<tr>
<td>订单图片:</td>
<td><input type="file" name="wuliuphoto" value="" /></td>
</tr>
<tr>
<td> </td>
<td><input type="image" border="0" src="../images/button_submit.gif" name="update" /></td>
</tr>
</table>
</form>
提交图片,请问在后台的java文件中怎么获取到该图片,语句怎么写,后台使用的是spring框架 展开
<form action="<c:url value="/shop/getorderphoto.do"/>" method="POST">
<table align="center" border="0">
<tr>
<td colspan="2">请输入订单详细图片
<br /> </td>
</tr>
<tr>
<td>订单图片:</td>
<td><input type="file" name="wuliuphoto" value="" /></td>
</tr>
<tr>
<td> </td>
<td><input type="image" border="0" src="../images/button_submit.gif" name="update" /></td>
</tr>
</table>
</form>
提交图片,请问在后台的java文件中怎么获取到该图片,语句怎么写,后台使用的是spring框架 展开
推荐于2017-07-22
展开全部
上传图片 后台获取的时候直接从数据库拿路径
下面这是servlet的内容:
package demo;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class DemoServlet extends HttpServlet {
private static final String UPLOAD_DIRECTORY = "upload";
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload sfu=new ServletFileUpload(factory);
sfu.setHeaderEncoding("UTF-8");
sfu.setProgressListener(new ProgressListener() {
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("文件大小为:"+pContentLength+",当前已处理:"+pBytesRead);
}
});
//判断提交上来的数据是否是上传表单的数据
if(!ServletFileUpload.isMultipartContent(request)){
PrintWriter writer= response.getWriter();
writer.println("Error:表单必须包含 enctype=multipart/form-data");
writer.flush();
return;
}
factory.setSizeThreshold(MEMORY_THRESHOLD);
//设置临时储存目录
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
//设置最大文件上传值
sfu.setFileSizeMax(MAX_FILE_SIZE);
//设置最大请求值(包含文件和表单数据)
sfu.setSizeMax(MAX_REQUEST_SIZE);
String uploadpath=getServletContext().getRealPath("./")+ File.separator+UPLOAD_DIRECTORY;
File file=new File(uploadpath);
if(!file.exists()){
file.mkdir();
}
try {
List<FileItem> formItems = sfu.parseRequest(request);
if(formItems!=null&&formItems.size()>0){
for(FileItem item:formItems){
if(!item.isFormField()){
String fileName=new File(item.getName()).getName();
String filePath=uploadpath+File.separator+fileName;
File storeFile=new File(filePath);
System.out.println(filePath);
item.write(storeFile);
request.setAttribute("message", "文件上传成功!");
}
}
}
} catch (Exception e) {
request.setAttribute("message", "错误信息:"+e.getMessage());
}
getServletContext().getRequestDispatcher("/demo.jsp").forward(request, response);
}
}
下面是jsp的内容,jsp放到webapp下,如果想放到WEB-INF下就把servlet里转发的路径改一下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="demo.do" enctype="multipart/form-data" method="post">
<input type="file" name="file1" />
<%
String message = (String) request.getAttribute("message");
%>
<%=message%>
<input type="submit" value="提交"/>
</form>
</body>
</html>
下面这是servlet的内容:
package demo;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class DemoServlet extends HttpServlet {
private static final String UPLOAD_DIRECTORY = "upload";
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload sfu=new ServletFileUpload(factory);
sfu.setHeaderEncoding("UTF-8");
sfu.setProgressListener(new ProgressListener() {
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("文件大小为:"+pContentLength+",当前已处理:"+pBytesRead);
}
});
//判断提交上来的数据是否是上传表单的数据
if(!ServletFileUpload.isMultipartContent(request)){
PrintWriter writer= response.getWriter();
writer.println("Error:表单必须包含 enctype=multipart/form-data");
writer.flush();
return;
}
factory.setSizeThreshold(MEMORY_THRESHOLD);
//设置临时储存目录
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
//设置最大文件上传值
sfu.setFileSizeMax(MAX_FILE_SIZE);
//设置最大请求值(包含文件和表单数据)
sfu.setSizeMax(MAX_REQUEST_SIZE);
String uploadpath=getServletContext().getRealPath("./")+ File.separator+UPLOAD_DIRECTORY;
File file=new File(uploadpath);
if(!file.exists()){
file.mkdir();
}
try {
List<FileItem> formItems = sfu.parseRequest(request);
if(formItems!=null&&formItems.size()>0){
for(FileItem item:formItems){
if(!item.isFormField()){
String fileName=new File(item.getName()).getName();
String filePath=uploadpath+File.separator+fileName;
File storeFile=new File(filePath);
System.out.println(filePath);
item.write(storeFile);
request.setAttribute("message", "文件上传成功!");
}
}
}
} catch (Exception e) {
request.setAttribute("message", "错误信息:"+e.getMessage());
}
getServletContext().getRequestDispatcher("/demo.jsp").forward(request, response);
}
}
下面是jsp的内容,jsp放到webapp下,如果想放到WEB-INF下就把servlet里转发的路径改一下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="demo.do" enctype="multipart/form-data" method="post">
<input type="file" name="file1" />
<%
String message = (String) request.getAttribute("message");
%>
<%=message%>
<input type="submit" value="提交"/>
</form>
</body>
</html>
展开全部
首先在html的form添加:enctype="multipart/form-data"
// Java代码
@RequestMapping("/upload" )
public String addUser(@RequestParam("file") CommonsMultipartFile[] files,HttpServletRequest request){
for(int i = 0;i<files.length;i++){
System.out.println("fileName---------->" + files[i].getOriginalFilename());
if(!files[i].isEmpty()){
int pre = (int) System.currentTimeMillis();
try {
//拿到输出流,同时重命名上传的文件
FileOutputStream os = new FileOutputStream("H:/" + new Date().getTime() + files[i].getOriginalFilename());
//拿到上传文件的输入流
FileInputStream in = (FileInputStream) files[i].getInputStream();
//以写字节的方式写文件
int b = 0;
while((b=in.read()) != -1){
os.write(b);
}
os.flush();
os.close();
in.close();
int finaltime = (int) System.currentTimeMillis();
System.out.println(finaltime - pre);
} catch (Exception e) {
e.printStackTrace();
System.out.println("上传出错");
}
}
}
return "/success";
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
图片要使用文件上传的方式。既然你使用spring框架的话,那就用它本身的上传配置。
你在spring配置文件中加上这个:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value=“10485760"/> <!--设置文件上传最大值字节:-->
</bean>
//后台
public String addUser(@RequestParam("file") MultipartFile myfile,HttpServletRequest request) throws IOException{
//下面这个方法可以实现文件上传到服务器
//不懂的话可以查下spring API
FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, myfile.getOriginalFilename()));
}
你在spring配置文件中加上这个:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value=“10485760"/> <!--设置文件上传最大值字节:-->
</bean>
//后台
public String addUser(@RequestParam("file") MultipartFile myfile,HttpServletRequest request) throws IOException{
//下面这个方法可以实现文件上传到服务器
//不懂的话可以查下spring API
FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, myfile.getOriginalFilename()));
}
追问
能不能把Java部分的代码写的详细一点,我不怎么懂Java,我只是做毕业设计的时候用一下,比如我要存到D盘的work目录下,请帮个忙,把程序补充完整吧,API我看不懂的
追答
FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(“D:\\work”, myfile.getOriginalFilename()));
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
不是有方法获取吗,好多年不写给忘了。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询