大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
和普通的上传请求一样,你可以使用commons-upload来解析请求,spring的话可以通过action的注解参数来获取上传的文件,jfinal可以用getFile()方法来获取。
创新互联公司坚持“要么做到,要么别承诺”的工作理念,服务领域包括:成都做网站、成都网站建设、企业官网、英文网站、手机端网站、网站推广等服务,满足客户于互联网时代的河北网站设计、移动媒体设计的需求,帮助企业找到有效的互联网解决方案。努力成为您成熟可靠的网络建设合作伙伴!
如果你想简单,可以以字节流的形式发送文件,webuploder有个参数sendAsBinary ,将其设置为true,这样你java后端用request.getInputStream()即可获取文件的字节流,文件名等参数你可以通过request.getParameter()方法获得。推荐你这么做,最简单的方式。
写一个servlet或jsp来接收,在servlet或jsp处理业务逻辑,后返回处理结果或新的数据
如jsp:
%@ page errorPage="/common/error/error.jsp" %
%@ page contentType="text/html;charset=GBK"%
%
String planeNumber = request.getParameter("planeNumber");
String planeType = com.aerolink.aocs.system.parameter.list.PlaneTypeFactory.getPlaneType(planeNumber);
response.getWriter().write(planeType);%
使用一些已有的组件帮助我们实现这种上传功能。常用的上传组件:Apache的CommonsFileUploadJavaZoom的UploadBeanjspSmartUpload以下,以FileUpload为例讲解1、在jsp端要注意enctype="multipart/form-data"然后只需要放置一个file控件,并执行submit操作即可2、web端核心代码如下:publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{request.setCharacterEncoding("UTF-8");DiskFileItemFactoryfactory=newDiskFileItemFactory();ServletFileUploadupload=newServletFileUpload(factory);try{Listitems=upload.parseRequest(request);Iteratoritr=items.iterator();while(itr.hasNext()){FileItemitem=(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());FiletempFile=newFile(item.getName());Filefile=newFile(sc.getRealPath("/")+savePath,tempFile.getName());item.write(file);request.setAttribute("upload.message","上传文件成功!");}else{request.setAttribute("upload.message","没有选择上传文件!");}}}}catch(FileUploadExceptione){e.printStackTrace();}catch(Exceptione){e.printStackTrace();request.setAttribute("upload.message","上传文件失败!");}request.getRequestDispatcher("/uploadResult.jsp").forward(request,response);}
Uploadify 是一个比较坑的东西,得用servlet, web.xml里配置 然后servlet接收
servlet
servlet-nameupload/servlet-name
servlet-classcom.action.upload/servlet-class
/servlet
servlet-mapping
servlet-nameupload/servlet-name
url-pattern/upload/FileUploadServlet/url-pattern
/servlet-mapping
servlet里代码
public void doGetAndPost(HttpServletRequest request,
HttpServletResponse response){
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e) {
logger.error("后台添加图片,request设置编码符失败! {}",e.getMessage());
}
DiskFileItemFactory fac = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fac);
upload.setHeaderEncoding("utf-8");
List fileList = null;
try {
fileList = upload.parseRequest(request);
} catch (FileUploadException ex) {
ex.printStackTrace();
return;
}
String imageName = null;
IteratorFileItem it = fileList.iterator();
while (it.hasNext()) {
FileItem item = it.next();
if (!item.isFormField()) {
Random r = new Random();
int rannum = (int) (r.nextDouble() * (9999 - 1000 + 1)) + 1000;
imageName=getNowStrDate() + rannum;
FileBean fileBean = new FileBean();
fileBean.setFileName(item.getName());
fileBean.setFileExtension(item.getName().substring(item.getName().indexOf(".")+1));
FileBean flbn;
try {
//文件服务器处理上传图片
flbn = FastDFSUtil.upload(fileBean, item.getInputStream());
} catch (IOException e) {
logger.info("添加图片,上传文件服务器失败!",e);
}
}
}
}
/**
* 文件上传到微信服务器
* @param fileType 文件类型
* @param filePath 文件路径
* @return JSONObject
* @throws Exception
*/
public static JSONObject send(String fileType, String filePath) throws Exception {
String result = null;
File file = new File(filePath);
if (!file.exists() || !file.isFile()) {
throw new IOException("文件不存在");
}
/**
* 第一部分
*/
URL urlObj = new URL(""+ getAccess_token() + "type="+fileType+"");
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false); // post方式不能使用缓存
// 设置请求头信息
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
// 设置边界
String BOUNDARY = "----------" + System.currentTimeMillis();
con.setRequestProperty("Content-Type", "multipart/form-data; boundary="+ BOUNDARY);
// 请求正文信息
// 第一部分:
StringBuilder sb = new StringBuilder();
sb.append("--"); // 必须多两道线
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"file\";filename=\""+ file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
// 获得输出流
OutputStream out = new DataOutputStream(con.getOutputStream());
// 输出表头
out.write(head);
// 文件正文部分
// 把文件已流文件的方式 推入到url中
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
// 结尾部分
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
out.write(foot);
out.flush();
out.close();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
try {
// 定义BufferedReader输入流来读取URL的响应
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
//System.out.println(line);
buffer.append(line);
}
if(result==null){
result = buffer.toString();
}
} catch (IOException e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
throw new IOException("数据读取异常");
} finally {
if(reader!=null){
reader.close();
}
}
JSONObject jsonObj =new JSONObject(result);
return jsonObj;
}
package com.letv.dir.cloud.util;import com.letv.dir.cloud.controller.DirectorWatermarkController;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.*;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;/** * Created by xijunge on 2016/11/24 0024. */public class HttpRequesterFile { private static final Logger log = LoggerFactory.getLogger(HttpRequesterFile.class); private static final String TAG = "uploadFile"; private static final int TIME_OUT = 100 * 1000; // 超时时间 private static final String CHARSET = "utf-8"; // 设置编码 /** * 上传文件到服务器 * * @param file * 需要上传的文件 * @param RequestURL * 文件服务器的rul * @return 返回响应的内容 * */ public static String uploadFile(File file, String RequestURL) throws IOException {
String result = null;
String BOUNDARY = "letv"; // 边界标识 随机生成 String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; // 内容类型 try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true); // 允许输入流 conn.setDoOutput(true); // 允许输出流 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); // 请求方式 conn.setRequestProperty("Charset", CHARSET); // 设置编码 conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);