java上传图片或者文件
package com.pat.postrequestemulator;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
public class PostRequestEmulator
{
public static void main(String[] args)throws Exception
{
// 设定服务地址
String serverUrl ="http://127.0.0.1:8080/test/upload";
// 设定要上传的普通Form Field及其对应的value
ArrayList<FormFieldKeyValuePair>ffkvp = new ArrayList<FormFieldKeyValuePair>();
ffkvp.add(new FormFieldKeyValuePair("tasktype", "1"));
ffkvp.add(new FormFieldKeyValuePair("dataname", "zhangsan"));
// 设定要上传的文件
ArrayList<UploadFileItem>ufi = new ArrayList<UploadFileItem>();
ufi.add(new UploadFileItem("upload3", "C:\\124038.jpg"));
// ufi.add(new UploadFileItem("upload2", "E:\\full.jpg"));
// ufi.add(new UploadFileItem("upload3", "E:\\dyz.txt"));
HttpPostEmulator hpe = new HttpPostEmulator();
String response =hpe.sendHttpPostRequest(serverUrl, ffkvp, ufi);
System.out.println("Responsefrom server is: " + response);
}
}
class HttpPostEmulator
{
//每个post参数之间的分隔。随意设定,只要不会和其他的字符串重复即可。
private static final String BOUNDARY ="----------HV2ymHFg03ehbqgZCaKO6jyH";
public String sendHttpPostRequest(String serverUrl,
ArrayList<FormFieldKeyValuePair>generalFormFields,
ArrayList<UploadFileItem>filesToBeUploaded) throws Exception
{
// 向服务器发送post请求
URL url = new URL(serverUrl/*"http://127.0.0.1:8080/test/upload"*/);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
// 发送POST请求必须设置如下两行
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection","Keep-Alive");
connection.setRequestProperty("Charset","UTF-8");
connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);
// 头
String boundary = BOUNDARY;
// 传输内容
StringBuffer contentBody =new StringBuffer("--" + BOUNDARY);
// 尾
String endBoundary ="\r\n--" + boundary + "--\r\n";
OutputStream out =connection.getOutputStream();
// 1. 处理文字形式的POST请求
for(FormFieldKeyValuePair ffkvp : generalFormFields)
{
contentBody.append("\r\n")
.append("Content-Disposition: form-data; name=\"")
.append(ffkvp.getKey() + "\"")
.append("\r\n")
.append("\r\n")
.append(ffkvp.getValue())
.append("\r\n")
.append("--")
.append(boundary);
}
String boundaryMessage1 =contentBody.toString();
out.write(boundaryMessage1.getBytes("utf-8"));
// 2. 处理文件上传
for(UploadFileItem ufi :filesToBeUploaded)
{
contentBody = new StringBuffer();
contentBody.append("\r\n")
.append("Content-Disposition:form-data; name=\"")
.append(ufi.getFormFieldName() +"\"; ") // form中field的名称
.append("filename=\"")
.append(ufi.getFileName() +"\"") //上传文件的文件名,包括目录
.append("\r\n")
.append("Content-Type:application/octet-stream")
.append("\r\n\r\n");
String boundaryMessage2 = contentBody.toString();
out.write(boundaryMessage2.getBytes("utf-8"));
// 开始真正向服务器写文件
File file = new File(ufi.getFileName());
DataInputStream dis= new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut =new byte[(int) file.length()];
bytes =dis.read(bufferOut);
out.write(bufferOut,0, bytes);
dis.close();
contentBody.append("------------HV2ymHFg03ehbqgZCaKO6jyH");
String boundaryMessage = contentBody.toString();
out.write(boundaryMessage.getBytes("utf-8"));
//System.out.println(boundaryMessage);
}
out.write("------------HV2ymHFg03ehbqgZCaKO6jyH--\r\n".getBytes("UTF-8"));
// 3. 写结尾
out.write(endBoundary.getBytes("utf-8"));
out.flush();
out.close();
// 4. 从服务器获得回答的内容
String strLine="";
String strResponse ="";
InputStream in =connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in,"utf8"));
while((strLine =reader.readLine()) != null)
{
strResponse +=strLine +"\n";
}
//System.out.print(strResponse);
return strResponse;
}
}
class FormFieldKeyValuePair implements Serializable
{
private static final long serialVersionUID = 1L;
// The form field used for receivinguser's input,
// such as "username" in "<inputtype="text" name="username"/>"
private String key;
// The value entered by user in thecorresponding form field,
// such as "Patrick" the abovementioned formfield "username"
private String value;
public FormFieldKeyValuePair(String key, String value)
{
this.key = key;
this.value = value;
}
public String getKey()
{
return key;
}
public void setKey(String key)
{
this.key = key;
}
public String getValue()
{
return value;
}
public void setValue(String value)
{
this.value = value;
}
}
class UploadFileItem implements Serializable
{
private static final long serialVersionUID = 1L;
// The form field name in a form used foruploading a file,
// such as "upload1" in "<inputtype="file" name="upload1"/>"
private String formFieldName;
// File name to be uploaded, thefileName contains path,
// such as "E:\\some_file.jpg"
private String fileName;
public UploadFileItem(String formFieldName, String fileName)
{
this.formFieldName =formFieldName;
this.fileName = fileName;
}
public String getFormFieldName()
{
return formFieldName;
}
public void setFormFieldName(String formFieldName)
{
this.formFieldName =formFieldName;
}
public String getFileName()
{
return fileName;
}
public void setFileName(String fileName)
{
this.fileName = fileName;
}
}
java上传图片或者文件的更多相关文章
- java上传图片或文件
转载至:http://www.xdx97.com/#/single?bid=8b351a73-922c-eadc-512e-9e248a3efde9 前端通过form表单用post方式提交文件,后台进 ...
- java上传图片到数据库,涉及压缩文件zip/rar上传等
项目中有这个需求: 1)上传文件通过公司平台的校验,校验成功后,通过接口,返回文件流: 2)我们根据这个文件流进行操作.这里,先将文件流复制文件到项目临时目录WEB-INF/temp;文件使用完毕,删 ...
- ajax 提交所有表单内容及上传图片(文件),以及单独上传某个图片(文件)
我以演示上传图片为例子: java代码如下(前端童鞋可以直接跳过看下面的html及js): package com.vatuu.web.action; import java.io.File; imp ...
- JSP+java上传图片到服务器,并将地址保存至MYSQL + JSP网页显示服务器的图片
这两天遇到个需求——用户头像修改功能. 查了好多资料,不是代码不全,就是某些高端框架,卡了好久,今已实现,分享给大家,如果有更好的方法,非常感谢可以在下方评论区写出 一.整体项目架构 二.web.xm ...
- Java FtpClient 实现文件上传服务
一.Ubuntu 安装 Vsftpd 服务 1.安装 sudo apt-get install vsftpd 2.添加用户(uftp) sudo useradd -d /home/uftp -s /b ...
- Java实现FTP文件与文件夹的上传和下载
Java实现FTP文件与文件夹的上传和下载 FTP 是File Transfer Protocol(文件传输协议)的英文简称,而中文简称为"文传协议".用于Internet上的控制 ...
- java中的文件读取和文件写出:如何从一个文件中获取内容以及如何向一个文件中写入内容
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.Fi ...
- java 上传图片
1.导入smartupload.jar包 ,添加uploadIMG.jsp,upfileIMG.jsp. 2.需要在项目下面建立一个保存文件的文件夹pic或者upload 3.在调用的地方调用子框架u ...
- java分享第十六天( java读取properties文件的几种方法&java配置文件持久化:static块的作用)
java读取properties文件的几种方法一.项目中经常会需要读取配置文件(properties文件),因此读取方法总结如下: 1.通过java.util.Properties读取Propert ...
随机推荐
- thinkpad e450 win7黑苹果macos 10.10.5(网/显/声卡驱动)安装成功
首先上图: 过程: 1.使用变色龙安装macos 10.10.5懒人版黑苹果 2.使用Haswell破解内核替换,成功进入系统 2.5.使用Hackintosh Vietnam Tool 1.9.6以 ...
- LSD-SLAM深入学习(3)-代码解析
前言 在LSD-SLAM深入学习(2)中我们已经对算法进行分析,此处假设读者对于ros的基本操作都已经很熟悉,而且已经编写了一定量的的代码,我们直接上干货.此处分析的程序如下 main_live_od ...
- Quartz.net 定时调度CronTrigger时间配置格式说明
1. CronTrigger时间格式配置说明 CronTrigger配置格式: 格式: [秒] [分] [小时] [日] [月] [周] [年] 序号 说明 是否必填 允许填写的值 允许的通配符 ...
- Python Decorator分析
decorator本身是一个函数,这个函数的功能是接受被修饰的函数(decorated)作为参数,返回包装函数(wrapper)替换被修饰函数(decorated). @decorator func ...
- MFC字符串转化成16进制
//CString m_str = _T("11"); //USES_CONVERSION; //char *m_cc = T2A(m_str); //BYTE m_bb; //s ...
- android源码环境下用mmm/mm编译模块,输出编译log到文件的方法
android源码环境下用mmm/mm编译模块,输出编译log到文件的方法 1,在android目录下直接用mmm命令编译, log信息保存在android目录下 mmm packages/apps/ ...
- CSV的导入导出
using System; using System.Data; using System.IO; namespace COMMON { public class CSVhelperClass { / ...
- css3之背景新属性
background属性 属性 描述 background-origin 背景图片的定位区域 background-size 背景图片尺寸 background-image:url(),url();允 ...
- LeetCode(115) Distinct Subsequences
题目 Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequen ...
- 区间型DP
区间型DP是一类经典的动态规划问题,主要特征是可以先将大区间拆分成小区间求解最后由小区间的解得到大区间的解. 有三道例题 一.石子合并 在一个圆形操场的四周摆放N堆石子,现要将石子有次序地合并成一堆. ...