android上传图片,后台在同一路径下不停的写同一图片,导致硬盘空间不足

ewwerpm 2017-11-18 11:48:52
Android端代码
public class MainActivity extends ActionBarActivity {

private Button captureAndShowBtn, uploadMyBtn,okBtn;//uploadAfterBtn
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Uri mPhotoUri;// fileUri
// private boolean isTakePhoto= true;
// private Intent intent ;
private ImageView imgV;
private String requestURL = "http://192.168.1.123:8080/Report/UploadShipServlet";
private String request;
private int index = 0;
private int mProgressStatus = 0;
//private static final String TAG = "uploadFile";
private static final int TIME_OUT = 300*1000; //超时时间
private static final String CHARSET = "utf-8"; //设置编码
private final Handler mHandler = new Handler() {
//http://blog.csdn.net/pi9nc/article/details/9287773 ProgressBar进度条的使用
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what == 0x111) {
mProgressStatus = index;
//设置进度条当前的完成进度
bar.setProgress(mProgressStatus);
okBtn.setEnabled(false);
}else if(msg.what == 0x200){
bar.setVisibility(ProgressBar.GONE);
textView.setText("上传成功");
index=0;
okBtn.setEnabled(true);
}
}
};
private TextView textView;
private ProgressBar bar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}

//@TargetApi(Build.VERSION_CODES.GINGERBREAD)
private void initView() {
imgV = (ImageView) findViewById(R.id.resultImage);
captureAndShowBtn = (Button) findViewById(R.id.captureAndShowBtn);
okBtn=(Button)findViewById(R.id.okBtn);
bar = (ProgressBar)findViewById(R.id.bar);
bar.setVisibility(ProgressBar.INVISIBLE);

if (captureAndShowBtn != null)
captureAndShowBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {

Intent cameraIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE;
mPhotoUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
startActivityForResult(cameraIntent, 1);// REQUEST_CODE
}
});
uploadMyBtn = (Button) findViewById(R.id.uploadMyBtn);
textView =(TextView)findViewById(R.id.textView1);
uploadMyBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bar.setVisibility(ProgressBar.VISIBLE);
new Thread() { //这里必须起一个线程,因为网络相关的不能在主线程里
File file = new File(mPhotoUri.getPath());
@Override
public void run() {
super.run();
if(index < 100) {//while
//doWork();
//index= UploadUtil.getIndexUp();

if(file.exists()){
request = uploadFile(file, requestURL);
Log.i("UpLoadActivity", request);
//}
}
}
}

}.start();//.start();


}
});
}
/* android上传文件到服务器
* @param file 需要上传的文件
* @param RequestURL 请求的url
* @return 返回响应的内容
*/
private String uploadFile(File file, String RequestURL){
String result = null;
String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成
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);
conn.connect();

if(file!=null){
/**
* 当文件不为空,把文件包装并且上传
*/
DataOutputStream dos = new DataOutputStream( conn.getOutputStream());
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
/**
* 这里重点注意:
* name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名的 比如:abc.png
*/

sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END);
sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END);
sb.append(LINE_END);
dos.write(sb.toString().getBytes());
long totalSize = getFileSize(file);
InputStream is = new FileInputStream(file);
long tempIndex=0;
byte[] bytes = new byte[1024];
int len = 0;
while((len=is.read(bytes))!=-1){
dos.write(bytes, 0, len);
tempIndex+=len;
index = (int) (tempIndex * 100.0f / totalSize);
Message msg = Message.obtain();
msg.what = 0x111;
this.mHandler.sendMessage(msg);
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
dos.write(end_data);
dos.flush();
/**
* 获取响应码 200=成功
* 当响应成功,获取响应的流
*/
int res = conn.getResponseCode();
if(res==200){
InputStream input = conn.getInputStream();
StringBuffer sb1= new StringBuffer();
int ss ;
while((ss=input.read())!=-1){
sb1.append((char)ss);
}
result = sb1.toString();
Message msg = Message.obtain();
msg.what = 0x200;
this.mHandler.sendMessage(msg);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
return result;
}

后台代码
package servlet;
public class UploadShipServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String path,serverFileName,timeStamp;
public UploadShipServlet() {
super();
}

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();

// 创建文件项目工厂对象
DiskFileItemFactory factory = new DiskFileItemFactory();

// 设置文件上传路径
//String upload = this.getServletContext().getRealPath("/");//H:\apache-tomcat-8.0.46-windows-x64\apache-tomcat-8.0.46\webapps\Report\

// 获取系统默认的临时文件保存路径,该路径为Tomcat根目录下的temp文件夹
String temp = System.getProperty("java.io.tmpdir");//C:\Users\zdl\AppData\Local\Temp\
// 设置缓冲区大小为 5M
factory.setSizeThreshold(1024 * 1024 * 5);
// 设置临时文件夹为temp
factory.setRepository(new File(temp));
// 用工厂实例化上传组件,ServletFileUpload 用来解析文件上传请求
ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

// 解析结果放在List中
try {
List<FileItem> list = servletFileUpload.parseRequest(request);

for (FileItem item : list) {
//name=IMG_20171018_093125.jpg, StoreLocation=C:\Users\zdl\AppData\Local\Temp\ upload_edae6439_57b2_4d38_afda_209f662d3f03_00000000.tmp, size=48265 bytes, isFormField=false, FieldName=img
String name = item.getFieldName();
InputStream is = item.getInputStream();

if (name.contains("content")) {
System.out.println(inputStream2String(is));
} else if (name.contains("img")) {
try {
timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
serverFileName = "IMG_"+ timeStamp +"-"+UUID.randomUUID().toString()+".jpg";
path = "c:\\check_img\\"+serverFileName;
inputStream2File(is, path);//输入流转成文件
break;
} catch (Exception e) {
e.printStackTrace();
}
}
}
out.write(serverFileName);
out.flush();
out.close();
} catch (org.apache.commons.fileupload.FileUploadException e1) {
e1.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}


}

// 流转化成字符串
public static String inputStream2String(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i = -1;
while ((i = is.read()) != -1) {
baos.write(i);
}
return baos.toString();
}

// 流转化成文件
public static void inputStream2File(InputStream is, String savePath) throws Exception {
File file = new File(savePath);
InputStream inputSteam = is;
//BufferedInputStream fis = new BufferedInputStream(inputSteam);
FileOutputStream fos = new FileOutputStream(file);
byte[]buffer=new byte[1024];
int len=0;
while ((len=inputSteam.read(buffer))!=-1) {
fos.write(buffer,0, len);
}
fos.flush();
fos.close();
inputSteam.close();
System.out.println("文件保存路径为:" + savePath);
}
}

已经出现过2次,但无法重现
...全文
196 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
r00_a2lBUR 2017-11-20
  • 打赏
  • 举报
回复
引用 4 楼 ewwerpm 的回复:
[quote=引用 2 楼 r00_a2lBUR 的回复:] 没有判断是否写入成功吗?
另外,我还问下,如果图片超过5M,后台程序会怎么处理?我 的照片超过5m,也上传的好好的,但不知道程序是如何运行的?[/quote] 我想可以首先告诉服务器要上传文件的大小,然后按照5M分割发送,服务器那边接收到之后,先保存成临时文件,再拼合起来。
r00_a2lBUR 2017-11-18
  • 打赏
  • 举报
回复
没有判断是否写入成功吗?
ewwerpm 2017-11-18
  • 打赏
  • 举报
回复
我后台用这段代码接受文件,期望收到并写硬盘成功后,返回200 和服务器文件名,Android端收到200后将“确定”按钮变为可用。可是服务器一直在不停的写同一个接收到的文件(大小一致,文件名不一样,重命名了),前台的“确定”按钮也在“可用”“不可用”之间来回变,可能是什么原因?
ewwerpm 2017-11-18
  • 打赏
  • 举报
回复
引用 2 楼 r00_a2lBUR 的回复:
没有判断是否写入成功吗?
另外,我还问下,如果图片超过5M,后台程序会怎么处理?我 的照片超过5m,也上传的好好的,但不知道程序是如何运行的?
ewwerpm 2017-11-18
  • 打赏
  • 举报
回复
引用 2 楼 r00_a2lBUR 的回复:
没有判断是否写入成功吗?
什么意思?代码要如何写?inputStream2File方法就是写文件的,循环结束后,就会输出文件路径。这个问题的关键是不能复现,都是偶然发生了两次,但不知道如何复现。。。

80,351

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧