这里说一下后台是如何处理上传文件的,用的是java。
上传的功能使用了apache的通用jar包,可以在这里下载。
java代码如下,简单说明下:
1.设置上传目录,这个目录是指web服务器所在机器的目录
2.防止乱码的设置
3.上传功能写在action里,示例直接使用了默认的方法名doPost,如果你要用struts之类的,可以定义自己的方法名称
package com.nstar.orderexpress.web;
import javax.servlet.http.HttpServlet;
import org.apache.log4j.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.util.List;
import org.apache.commons.fileupload.FileUploadException;
import java.util.Iterator;
import org.apache.commons.fileupload.FileItem;
import java.io.File;
import java.io.UnsupportedEncodingException;
import org.apache.commons.lang.ObjectUtils;
public class FileUploadAction extends HttpServlet{
private static Logger logger = Logger.getLogger(FileUploadAction.class.getName());
private int maxPostSize = 100 * 1024 * 1024;
private String uploadPath = "D:\\upload\\";
public FileUploadAction() {
}
//文件上传
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
logger("begin upload");
try {
request.setCharacterEncoding("UTF-8");//防止文件名称带有汉字后传到服务器乱码
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setContentType("text/html; charset=UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 4);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(maxPostSize);
logger("request================"+ObjectUtils.toString(request));
List fileItems = null;
try {
fileItems = upload.parseRequest(request);
logger("===================="+ObjectUtils.toString(fileItems));
Iterator iter = fileItems.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
log(item.toString());
if (!item.isFormField()) {
String name = item.getName();
logger("file name = "+name);
try {
item.write(new File(uploadPath + name));
}
catch (Exception ex) {
logger(ex.getMessage());
}
}
}
}
catch (FileUploadException ex1) {
logger("FileUploadException->"+ex1.getMessage());
}
}
private void logger(String info){
System.out.println(info);
}
}
文件上传基本上就这么多了,可以在此基础上去扩展你想要的功能。