简体   繁体   中英

Cant upload a file using rest web service

I need to upload a file(image or any file) to server using java web service. The code which am used is mentioned. But unfortunately it doesn't work.

My Code:

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;


@Path("/webService")
public class ImageUpload {
    @POST
    @Path("/uploadImage")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public String uploadFile(@FormDataParam("file") InputStream uploadedInputStream,
            @FormDataParam("file") FormDataContentDisposition fileDetail)
            {
        saveToDisk(uploadedInputStream,fileDetail);
        return "File Uploaded Successfully";
            }

    private void saveToDisk(InputStream uploadedInputStream,
            FormDataContentDisposition fileDetail) {
        // TODO Auto-generated method stub
        String uploadFileLocation="d://upload/" + fileDetail.getFileName();
        try
        {
            OutputStream out=new FileOutputStream(new File(uploadFileLocation));
            int read=0;
            byte[] bytes=new byte[1024];
            out=new FileOutputStream(new File(uploadFileLocation));
            while((read=uploadedInputStream.read(bytes))!=-1)
            {
                out.write(bytes, 0, read);

            }
            out.flush();
            out.close();
        }
        catch(Exception io)
        {
            io.printStackTrace();
        }
    }
}

My Html file:

<html>
<body>
<h1>Upload file to a RFestFul Web Service</h1>
<form action="http://localhost:8080/ImageUpload_demo/webService/uploadImage" method="post" enctype="multipart/form-data">
<label for="file"> Select a file to be uploaded</label>
<input type="file" name="file"> <br>
<input type="submit" value="Upload">
</form>

</body>
</html>

After running it throws, the requested resource is not available. And file is not uploaded at the specified location. May someone helps to get it out. Am new to this part.

This is most likely due to a file-system rights issue. Your service account running the application probably does not have write access to d:\\upload folder path. Based on your path, I am assuming you're running your web service on a Windows box. You will need to provide write privileges to the user account that starts the web server serving your service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM