您的位置:首页 > 编程语言 > Java开发

java模拟form表单上传图片

2017-10-24 17:00 288 查看
package file;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import org.apache.poi.hssf.usermodel.*;

import org.junit.Test;

import java.io.*;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.ArrayList;

import java.util.List;

public class UploadFileByForm {

@Test
public void updatePicTest() throws Exception {
String serverUrl = "http://xxx.com/uploadImage"; //上传图片接口

List<String[]> resultList = new ArrayList<>();

File dir = new File("D:/图片目录");

File[] files = dir.listFiles();

for(File f : files){
String srcPath = f.getAbsolutePath().replace("\\","/");

String result = uploadPic(serverUrl, srcPath);

if(StringUtils.isNotBlank(result)){
JSONObject jsonObject = JSONObject.fromObject(result);
if(jsonObject.has("org_img_uri")){
String orgValue = jsonObject.getString("org_img_uri");
String bigValue = jsonObject.getString("big_img_uri");
String smallValue = jsonObject.getString("small_img_uri");

String fileNo = srcPath.substring(srcPath.lastIndexOf("/") + 1, srcPath.lastIndexOf("."));

resultList.add(new String[]{fileNo,orgValue,bigValue,smallValue});

}
}
Thread.sleep(10); //休息10毫秒
}

exportToExcel(resultList);

}

/**
* 上传图片接口返回的结果,告知客户端图片上传后的存储地址
* @param serverUrl 服务接口
* @param srcPath 图片绝对路径
* @return
* @throws Exception

     */
private String uploadPic(String serverUrl,String srcPath) throws Exception{
URL url = new URL(serverUrl);

HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
//httpURLConnection.setChunkedStreamingMode(128 * 1024);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
String boundary = "--WebKitFormBoundaryE19zNvXGzXaLvS5C";
httpURLConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);

String twoHyphens = "--";
String end = "\r\n";
DataOutputStream dos = new DataOutputStream(httpURLConnection
.getOutputStream());

dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + end);
dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + srcPath.substring(srcPath.lastIndexOf("/") + 1) + "\"" + end);
dos.writeBytes(end);
FileInputStream fis = new FileInputStream(new File(srcPath));
byte[] buffer = new byte[8192]; // 8k
int count = 0;
while ((count = fis.read(buffer)) != -1) {
dos.write(buffer, 0, count);
}
fis.close();
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
dos.flush();
dos.close();

StringBuffer result = new StringBuffer();

if(httpURLConnection.getInputStream()!=null){
BufferedReader br = new BufferedReader(new InputStreamReader(
httpURLConnection.getInputStream(), "utf-8"));
String line = null;
while(br!=null && (line = br.readLine())!=null){
result.append(line);
}
br.close();
}

if(httpURLConnection.getErrorStream()!=null){
BufferedReader errorBr = new BufferedReader(new InputStreamReader(
httpURLConnection.getErrorStream(), "utf-8"));
String line = null;
System.out.println("****************************上传文件报错:"+srcPath);
while(errorBr!=null && (line = errorBr.readLine())!=null){
System.out.println(line);
}
System.out.println("****************************");
errorBr.close();
}

return result.toString();
}

/**
* 导出到excel
* @param list

     */
private void exportToExcel(List<String[]> list){
// 第一步,创建一个webbook,对应一个Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet("图片存储地址");
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
HSSFRow row = sheet.createRow(0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_LEFT); // 创建一个靠左格式

HSSFCell cell = row.createCell(0);
cell.setCellValue("序号");
cell.setCellStyle(style);
cell = row.createCell(1);
cell.setCellValue("原始图片");
cell.setCellStyle(style);
cell = row.createCell(2);
cell.setCellValue("大图片");
cell.setCellStyle(style);
cell = row.createCell(3);
cell.setCellValue("小图片");
cell.setCellStyle(style);

// 第五步,写入实体数据 实际应用中这些数据从数据库得到,

for (int i = 0; i < list.size(); i++)
{
row = sheet.createRow(i + 1);
String[] strings = list.get(i);
// 第四步,创建单元格,并设置值
for(int j=0;j<strings.length;j++){
row.createCell(j).setCellValue(strings[j]);
}
}
// 第六步,将文件存到指定位置
try
{
FileOutputStream fout = new FileOutputStream("C:/Users/admin/Desktop/图片存储地址.xls");
wb.write(fout);
fout.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

需要用到操作excel的jar包,有需要的可以从这里下载http://download.csdn.net/download/keketrtr/10038026
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: