import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@Path("/images")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public class ImageResource {
private static final String SERVER_UPLOAD_LOCATION_FOLDER = "C://";
@POST
@Produces(MediaType.APPLICATION_JSON)
public String uploadStatePolicy(@Context HttpServletRequest request) {
try {
String fileName = saveFile(request);
if (!fileName.equals("")) {
} else {
}
} catch (Exception ex) {
}
return "";
}
/**
* 文件下载
*
* @throws UnsupportedEncodingException
* @throws IOException
*/
@GET
@Path("/download")
@Produces(MediaType.TEXT_PLAIN)
public String downloadFile(@Context HttpServletRequest request,
@Context HttpServletResponse response,
@QueryParam("fileName") String fileName)
throws UnsupportedEncodingException {
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
Boolean isOnLine = true; // 是否在线浏览
// 得到下载文件的名字
String fileNameStr = java.net.URLDecoder.decode(fileName, "utf-8");
// 解决中文乱码问题
// String filename=new
// String(request.getParameter("filename").getBytes("iso-8859-1"),"gbk");
StringBuffer path = new StringBuffer(fileNameStr);
File file = new File(path.toString());
FileInputStream fis = null;
BufferedInputStream buff = null;
OutputStream myout = null;
try {
if (!file.exists()) {
response.sendError(404, "File not found!");
return "";
}
response.reset();
if (isOnLine) { // 在线打开方式
URL u = new URL("file:///" + path.toString());
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename="
+ new String(file.getName().getBytes("gbk"),
"iso-8859-1"));
} else { // 纯下载方式
// 设置response的编码方式
response.setContentType("application/x-msdownload");
// 写明要下载的文件的大小
response.setContentLength((int) file.length());
// 设置附加文件名(解决中文乱码)
response.setHeader("Content-Disposition",
"attachment;filename="
+ new String(file.getName().getBytes("gbk"),
"iso-8859-1"));
}
fis = new FileInputStream(file);
buff = new BufferedInputStream(fis);
byte[] b = new byte[1024];// 相当于我们的缓存
long k = 0;// 该值用于计算当前实际下载了多少字节
// 从response对象中得到输出流,准备下载
myout = response.getOutputStream();
while (k < file.length()) {
int j = buff.read(b, 0, 1024);
k += j;
// 将b中的数据写到客户端的内存
myout.write(b, 0, j);
}
// 将写入到客户端的内存的数据,刷新到磁盘
myout.flush();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (buff != null)
buff.close();
if (myout != null)
myout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return "";
}
private String saveFile(HttpServletRequest request) {
String fileName = "";
try {
if (ServletFileUpload.isMultipartContent(request)) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
if (items != null) {
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (!item.isFormField() && item.getSize() > 0) {
fileName = processFileName(item.getName());
try {
item.write(new File(
SERVER_UPLOAD_LOCATION_FOLDER
+ fileName));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
} catch (Exception e) {
}
return fileName;
}
private String processFileName(String fileNameInput) {
String fileNameOutput = null;
fileNameOutput = fileNameInput.substring(
fileNameInput.lastIndexOf("\\") + 1, fileNameInput.length());
return fileNameOutput;
}
}
app中调用上传功能 使用了async-http异步请求开源项目。
public class HTTPCONFIG {
public static String IP = "http://192.168.191.1:8080/THwebservice/rest/";
public static String Method_UploadIcon = "images";
public static String Method_downloadimage = "images/download?fileName=";
}
private void fileupload() {
// TODO Auto-generated method stub
String urlString = HTTPCONFIG.IP + HTTPCONFIG.Method_UploadIcon;
InputStream myInputStream = null;
try {
myInputStream = new FileInputStream(picFileFullName);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
RequestParams params = new RequestParams();
params.put("secret_passwords", myInputStream, clanname + ".png");
HttpUtil.post(urlString, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
byte[] responseBody) {
// TODO Auto-generated method stub
Toast("创建成功");
Message msg = new Message();
msg.what = 1;
handler.sendMessage(msg);
new File(picFileFullName).delete();
}
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
// TODO Auto-generated method stub
Toast("创建失败,请重试");
};
});
}
下载功能
直接在url上面加上文件名即可
比如 http://192.168.191.1:8080/THwebservice/rest/images/download?fileName=123.png